zoukankan      html  css  js  c++  java
  • 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对象。

  • 相关阅读:
    隐私保护政策
    童真儿童简笔画
    方块十字消
    iOS 判断一断代码的执行时间(从网上看的,自己实现一下)
    iOS BLOCK回调:(妖妖随笔)
    typedef struct
    #define和预处理指令
    UIActivityIndicatorView
    Expected a type 的错误
    iOS 本地化字符串—(妖妖随笔)
  • 原文地址:https://www.cnblogs.com/q28633999/p/2078381.html
Copyright © 2011-2022 走看看