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

  • 相关阅读:
    day 26 python2和python3的区别 模块logging 的高级版,collections 模块,random模块
    常用模块:time,os,sys,rondom
    模块 hashlib(算法) configparser(配置) logging(日志)
    序列化,json pickle,shelve
    面向对象的封装,多态,单例模式
    属性,类方法,静态方法,反射
    面向对象的接口类 以及鸭子类型
    面向对象的继承
    面向对象的介绍
    reset internet explorer settings with registry
  • 原文地址:https://www.cnblogs.com/q28633999/p/2078381.html
Copyright © 2011-2022 走看看