如何使用来自两个不同独立表的数据创建单个json文件 [英] how to create single json file using data from two different independent tables

查看:223
本文介绍了如何使用来自两个不同独立表的数据创建单个json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个json文件,其中的数据采用这种格式

i want to generate a json file in which data is in this format

var JSON = {
    menu: [
        {id: '0',sub: [
            {name: 'lorem ipsum 0-0',link: '0-0', sub: null},
            {name: 'lorem ipsum 0-1',link: '0-1', sub: null},
            {name: 'lorem ipsum 0-2',link: '0-2', sub: null}
            ]
        },
        {id: '1',sub: null},
        {id: '2',sub: [
            {name: 'lorem ipsum 2-2',link: '2-2', sub: [
                {name: 'lorem ipsum 2-2-0',link: '2-2-0', sub: null},
                {name: 'lorem ipsum 2-2-1',link: '2-2-1', sub: null},
                {name: 'lorem ipsum 2-2-2',link: '2-2-2', sub: null}                
            ]},
            ]
        },
    ]
}


id来自一个表和名称,链接来自同一数据库的另一个表

我无法以这种方式获取适当的查询来获取json文件

还可以在asp.net4.0中使用newtonsoft json


id comes from one table and name, link comes from another table of same database

i m not able to get proper queries to get json file this way

also m using newtonsoft json in asp.net4.0

推荐答案

在服务器端创建类,如下所示;

Create class in server side as below;

[DataContract]
class MainMenu{
[DataMember]
public int id;

[DataMember]
public SubMenu[] sub;
}

[DataContract]
class SubMenu
{
[DataMember]
public string name;

[DataMember]
public string link;

[DataMember]
public SubMenu[] sub;
}



现在,您需要创建一个MainMenu数组,并根据表中的信息填充它们.
MainMenu [] oMainMenues;

然后,如果您使用MVC,则可以从Controller类返回oMainMenues作为JSON对象.

如果仍然要创建文件,或者要作为客户字符串返回以在客户端形成JSon对象,则可以;您可以按以下方式使用JSon序列化器.



Now you need to create an array of MainMenu and populate them as per the information in the tables.
MainMenu[] oMainMenues;

Then you could return the oMainMenues as JSON object from Controller class if you use MVC.

If you want create a file anyway or want to return as customer string to form the JSon object in the client side; you could use the JSon serializer as following way.

MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MainMenu[]));
ser.WriteObject(YourStream, oMainMenues);



您可以参考followinf文章以获取更多相关信息;
如何:对JSON数据进行序列化和反序列化 [ ^ ]



You could refer to followinf article for more related information;
How to: Serialize and Deserialize JSON Data[^]


这篇关于如何使用来自两个不同独立表的数据创建单个json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆