下面一个json格式图(说一下,json 其实就是js 数组和对象的一种字符串表现形式 var obj=[] 或者var obj={} )
var json= {} 如下
从图中看 json中有两个成员分别是 total 和 ship(而ship里面有多个对象,那么我们就知道 ship是一个List<ship>列表)
下面我们在C#中模拟输出此效果
public class JsonHelper { ////// JSON序列化 /// public static string JsonSerializer(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; } /// /// JSON反序列化 /// public static T JsonDeserialize(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } }
//上面jsonHelp是帮助类
public class rows { public int itemid { get; set; } public int productid { get; set; } public string listprice { get; set; } public string unitcost { get; set; } public string status { get; set; } public string attr1 { get; set; } } public class Product { public int total { get; set; } public Listship { get; set; } //列表集对像 属性 }
protected void Page_Load(object sender, EventArgs e) { Product prt = new Product(); //主对象 rows r = new rows(); Listlist_row = new List (); //列表 list for (int i = 0; i < 3; i++) { r.itemid = i; r.productid = i; r.listprice = "ss_" + i; r.unitcost = "un_" + i; r.status = "Status" + i; r.attr1 = "atrr" + i; list_row.Add(r); } prt.total = 10; prt.ship = list_row; Response.Write(JsonHelper.JsonSerializer (prt)); //序列化输出 }
最后昨到上面输出的json字符串