2016-03-29 71 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)); 

是否有簡單的方法來修改此?