2016-03-29 10 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 

上記のテーブルから以下のようなjsonデータを、asp.netを使用してどのように生成できますか?2つのデータベーステーブルからネストされた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から/ toに変換することができます。答えを

[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)); 

これを簡単に修正する方法はありますか?

関連する問題