#table1# pid property address 1 property1 Ashfield 2 property2 Burwood #table2# id images pid 1 img1 1 2 img2 1 3 img3 2
如何使用c#using asp.net生成如上表所示的json数据?
property[
{
id: 1,
property: property1,
address: Ashfield,
images:[
images: img1,
images: img2
]},
id: 2,
property: property2,
address: Burwood,
images:[
images: img3
]}
]
答案 0 :(得分:1)
只需将嵌套对象构造为类,然后序列化为JSON。
只要您可以将JSON对象表示为类结构,就可以将easilly转换为/从中转换。
[Table(name="address")]
public class Address{
[Datamember(Name="images")]
public IEnumerable<Image> Images{get;set;}
}
答案 1 :(得分: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"
}
]
}
]
答案 2 :(得分: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));
有没有简单的方法来修改它?