public class Corporation {
public string remark { get; set; } public string version { get; set; } public string @operator { get; set; } }
public class TenderDoc { public string tenderdocid { get; set; } public Corporation corporation { get; set; } public string context { get; set; }public string @operator { get; set; } }
public class Root { public List<TenderDoc> datas { get; set; } public string flag{ get; set; } }
这样就定义了json的实体类。
Corporation cop = new Corporation(); cop.remark = "remark"; cop.version = "C#"; cop.@operator = "niap"; List<TenderDoc> listtd = new List<TenderDoc>(); for (int i = 0; i < 2; i++) { TenderDoc td = new TenderDoc(); td.tenderdocid = "NO1"; td.corporation = cop; td.context = "context"; td.@operator = "miap"; listtd.Add(td); } Root root = new Root() { datas = listtd, flag = "001" }; string jsonStr = JsonConvert.SerializeObject(root); Response.Write(jsonStr);
最后调用 JsonConvert.SerializeObject(),就可以将实体类对象转为JSON。
转换结果如下
{ "datas": [ { "tenderdocid": "NO1", "corporation": { "remark": "remark", "version": "C#", "operator": "niap" }, "context": "context", "operator": "miap" }, { "tenderdocid": "NO1", "corporation": { "remark": "remark", "version": "C#", "operator": "niap" }, "context": "context", "operator": "miap" } ], "flag": "001" }
原文:http://www.cnblogs.com/Nicolasap/p/5605853.html