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

  • 相关阅读:
    vue中Axios的封装和API接口的管理
    如何配置Webpack/Vue-CLI实现前端跨域(附跨域大全)
    前端面试几个重要知识点
    js常用函数
    JS中的枚举和不可枚举
    可配置性属性和不可配置性属性
    Object.create()和深拷贝
    JavaScript 中 call()、apply()、bind() 的用法
    从深入到通俗:Object.prototype.toString.call()
    js原生实现三级联动下拉菜单
  • 原文地址:https://www.cnblogs.com/aaa6818162/p/2251109.html
Copyright © 2011-2022 走看看