2016-03-29 54 views
0
 
#table1# 
pid property address 
1 property1 Ashfield 
2 property2 Burwood 

#table2# 
id images pid 
1 img1 1 
2 img2 1 
3 img3 2 

如何从上面的表中使用c#使用asp.net生成类似下面的json数据?从两个数据库表生成嵌套的json数据

property[ 
    { 
    id: 1, 
    property: property1, 
    address: Ashfield, 
    images:[ 
     images: img1, 
     images: img2 
    ]}, 
    id: 2, 
    property: property2, 
    address: Burwood, 
    images:[ 
     images: img3 
    ]} 
] 

回答

0
using (var ctx = new DatabaseEntities()) 
      { 
       var prop = from p in ctx.properties.Include("images") 
          select new 
          { 
           id = p.pid, 
           address = p.address, 
           property = p.property1, 
           images = (from img in p.images select new { images = img.images}) 
          }; 

       var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
       string jsonString = javaScriptSerializer.Serialize(prop.ToList()); 

       Console.WriteLine(jsonString); 
      } 

Json returned from the above code is: 

[ 
   { 
      "id": 1, 
      "address": "Ashfield", 
      "property": "property1", 
      "images": [ 
         { 
            "images": "img1" 
         }, 
         { 
            "images": "img2" 
         } 
      ] 
   }, 
   { 
      "id": 2, 
      "address": "Burwood", 
      "property": "property2", 
      "images": [ 
         { 
            "images": "img3" 
         } 
      ] 
   } 
] 
1

简单构造嵌套对象作为一类,然后序列化到JSON。

只要您可以将JSON对象表示为类结构,那么您可以将easilly转换为/从它转换。

[Table(name="address")] 
public class Address{ 
    [Datamember(Name="images")] 
    public IEnumerable<Image> Images{get;set;} 
} 
0

谢谢回答。我有此代码

 
DataTable dataTable = blproperty.PropertyAll(); 

     JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); 
     List > parentRow = new List >(); 
     Dictionary childRow; 
     foreach(DataRow row in dataTable.Rows) 
     { 
      childRow = new Dictionary (); 
      foreach(DataColumn col in dataTable.Columns) 
      { 
       childRow.Add(col.ColumnName, row[col]); 
      } 
      parentRow.Add(childRow); 
     } 
     context.Response.Write(jsSerializer.Serialize(parentRow)); 

是否有简单的方法来修改此?