使用到LitJSON 这个第三方dll,
用到的两个实体类
class jsonRoot { public string numPs { get; set; } public string qty { get; set; } }
class jsonClass { public int count { get; set; } public List<jsonRoot> root { get; set; } }
下面 json和类之间的互转
private void obj2Json() { jsonClass jc = new jsonClass(); jsonRoot jr = new jsonRoot(); jsonRoot jr2 = new jsonRoot(); List <jsonRoot> ljr =new List<jsonRoot> (); jr.numPs = "aaaaaaaa"; jr.qty = "111111"; jr2.numPs = "bbbbbbbb"; jr2.qty = "2222222"; ljr.Add (jr); ljr.Add (jr2); jc.count = 8; jc.root = ljr; string js = JsonMapper.ToJson(jc); Console.WriteLine(js); //打印出 {"count":8,"root":[{"numPs":"aaaaaaaa","qty":"111111"},{"numPs":"bbbbbbbb","qty":"2222222"}]} }
json 转obj
private void json2Obj() { string json = "{\"count\":8,\"root\":[{\"numPs\":\"aaaaaaaa\",\"qty\":\"111111\"},{\"numPs\":\"bbbbbbbb\",\"qty\":\"2222222\"}]}"; jsonClass thomas = JsonMapper.ToObject<jsonClass>(json); List < jsonRoot > ls= thomas.root; Console.WriteLine("-----", thomas.count); }
参考: http://www.oschina.net/p/litjson (dll 也可在此处下载)
原文:http://www.cnblogs.com/Marvellous/p/3986091.html