序列化Json-Newtonsoft.Json

C#中json数据的处理,把模型中的数据序列化为json

首先在项目中引用Newtonsoft.Json.dll

其下载地址和性能比较以及详情请查看:http://json.codeplex.com/

示例代码:

先建两个模型,以用在demo中

 1         public class xModle
 2         {
 3             public int xID { get; set; }
 4             public string xName { get; set; }
 5         }
 6 
 7         public class xJsonModel {
 8             public int xCount { get; set; }
 9             public List<xModle> xmodel { get; set; }
10         }

demo1:

1         public string JsonSerialize()
2         {
3             xModle item = new xModle { xID = 100, xName = "TestName" };
4             string JsonStr = JsonConvert.SerializeObject(item);
5             return JsonStr;
6         }

结果为:

{"xID":100,"xName":"TestName"}

demo2:

 1         public string JsonSerializeList()
 2         {
 3             xModle item1 = new xModle { xID = 100, xName = "TestName1" };
 4             xModle item2 = new xModle { xID = 200, xName = "TestName2" };
 5             string JsonStr = JsonConvert.SerializeObject(new[] { item1, item2 });
 6             //也可以用下面代码
 7             //List<xModle> list = new List<xModle>();
 8             //list.Add(item1);
 9             //list.Add(item2);
10             //string JsonStr = JsonConvert.SerializeObject(list);
11             return JsonStr;
12         }

结果为:

[{"xID":100,"xName":"TestName1"},{"xID":200,"xName":"TestName2"}]

demo3:

 1         public string JsonSerializeMore()
 2         {            
 3             xModle item1 = new xModle { xID = 100, xName = "TestName1" };
 4             xModle item2 = new xModle { xID = 200, xName = "TestName2" };
 5             List<xModle> list = new List<xModle>();
 6             list.Add(item1);
 7             list.Add(item2);
 8             xJsonModel xItem = new xJsonModel();
 9             xItem.xCount = list.Count;
10             xItem.xmodel = list;
11             string JsonStr = JsonConvert.SerializeObject(xItem);
12             return JsonStr;
13         }

结果为:

{"xCount":2,"xmodel":[{"xID":100,"xName":"TestName1"},{"xID":200,"xName":"TestName2"}]}


 反序列话就更简单了:如把上面这个结果反序列化

1             var x = JsonConvert.DeserializeObject<xJsonModel>(JsonStr);
2             return x.xmodel.FirstOrDefault().xName;//结果为TestName1

 

posted @ 2012-10-27 17:28  yuejin  阅读(9337)  评论(0编辑  收藏  举报