• 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对象。

  • 相关阅读:
    uva 10369 Arctic Network
    uvalive 5834 Genghis Khan The Conqueror
    uvalive 4848 Tour Belt
    uvalive 4960 Sensor Network
    codeforces 798c Mike And Gcd Problem
    codeforces 796c Bank Hacking
    codeforces 768c Jon Snow And His Favourite Number
    hdu 1114 Piggy-Bank
    poj 1276 Cash Machine
    bzoj 2423 最长公共子序列
  • 原文地址:https://www.cnblogs.com/q28633999/p/2078381.html
Copyright © 2020-2023  润新知