下面一個json格式圖(說一下,json 其實就是js 陣列和物件的一種字串表現形式 var obj=[] 或者var obj={} )
var json= {} 如下
從圖中看 json中有兩個成員分別是 total 和 ship(而ship裡面有多個物件,那麼我們就知道 ship是一個List<ship>列表)
下面我們在C#中模擬輸出此效果
public class JsonHelper { /// <summary> /// JSON序列化 /// </summary> public static string JsonSerializer<T>(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; } /// <summary> /// JSON反序列化 /// </summary> public static T JsonDeserialize<T>(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 List<rows> ship { get; set; } //列表集對像 屬性 }
protected void Page_Load(object sender, EventArgs e) { Product prt = new Product(); //主物件 rows r = new rows(); List<rows> list_row = new List<rows>(); //列表 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<Product>(prt)); //序列化輸出 }
最後昨到上面輸出的json字串