Json.Net 学习笔记(二) Linq to Json

using Newtonsoft.Json.Linq;

定义类:

    public class Product
    {
        public string Name { get; set; }
        public DateTime Expiry { get; set; }
        public decimal Price { get; set; }
        public string[] Sizes { get; set; }
    }

测试:

            Product product = new Product
            {
                Name = "Apple",
                Expiry = new DateTime(2010, 12, 18),
                Price = 3.99M,
                Sizes = new string[] { "Small", "Medium", "Large" }
            };

            string serializedJson = JsonConvert.SerializeObject(product);

            JObject o = JObject.Parse(serializedJson);
            string name = (string)o["Name"];
            //Apple
            JArray sizes = (JArray)o["Sizes"];
            string smallest = (string)sizes[0];
            Response.Write(name + "," + smallest + "<br/>");//输出Small
            //SelectToken
            smallest = (string)o.SelectToken("Sizes[0]");
            Response.Write(smallest + "<br/>");//输出Small
            //SelectToken with Linq
            var sizeLen5 = o["Sizes"].Select(i => (string)i).Where(i => i.Length == 5).ToList<string>();
           foreach (var size in sizeLen5)
            {
                Response.Write((string)size+ " <br/>");
            };//输出Small和Large

注:JArray表示一个Json集合,JObject表示一个Json对象。

posted @ 2011-06-11 15:03  资源收集  阅读(671)  评论(0编辑  收藏  举报