Newtonsoft.Json使用方法整理

序列化和反序列化JSON

在JSON文本和.NET对象之间转换的最快方法是使用Json序列化器…JsonSeriizer通过将.NET对象属性名称映射到JSON属性名称,并为您复制值,将.NET对象转换为其等效的JSON并再次返回。

  • JsonConvert
  • Json序列化器
  • JsonConvert
    对于要转换到JSON字符串和从JSON字符串转换的简单场景,序列化对象()和反序列化对象()方法在JsonSeriizer上提供了一个易于使用的包装器.

用JsonConvert序列化和反序列化JSON

Product product = new Product();

product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "ExpiryDate": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);

SerializeObject和DeserializeObject都具有一个JsonSerializerSettings对象。JsonSerializerSettings允许您在使用简单序列化方法的同时使用下面列出的许多JsonSeriizerSettings设置。

Json序列化器
有关如何序列化对象的更多控制,请使用Json序列化器可以直接使用。JsonSeriizer可以通过以下方式直接将JSON文本读写到流中JsonTextReader和JsonTextWriter…也可以使用其他类型的JsonWriter,例如JTokenReader/JTokenWriter,将对象从LINQ转换为JSON对象,或BsonReader/BsonWriter,转换为BSON或BSON。

用JsonSeriizer将JSON序列化为流

Product product = new Product();
product.ExpiryDate = new DateTime(2008, 12, 28);

JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore;

using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
    serializer.Serialize(writer, product);
    // {"ExpiryDate":new Date(1230375600000),"Price":0}
}

使用JSON路径查询JSON

JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");

string name = (string)o.SelectToken("Manufacturers[0].Name");

Console.WriteLine(name);
// Acme Co

decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");

Console.WriteLine(productPrice);
// 50

string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");

Console.WriteLine(productName);
// Elbow Grease

使用JSON路径和转义属性查询JSON

JObject o = JObject.Parse(@"{
  'Space Invaders': 'Taito',
  'Doom ]|[': 'id',
  ""Yar's Revenge"": 'Atari',
  'Government ""Intelligence""': 'Make-Believe'
}");

string spaceInvaders = (string)o.SelectToken("['Space Invaders']");
// Taito

string doom3 = (string)o.SelectToken("['Doom ]|[']");
// id

string yarsRevenge = (string)o.SelectToken("['Yar\\'s Revenge']");
// Atari

string governmentIntelligence = (string)o.SelectToken("['Government \"Intelligence\"']");
// Make-Believe

使用复杂JSON路径查询JSON

JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");

// manufacturer with the name 'Acme Co'
JToken acme = o.SelectToken("$.Manufacturers[?(@.Name == 'Acme Co')]");

Console.WriteLine(acme);
// { "Name": "Acme Co", Products: [{ "Name": "Anvil", "Price": 50 }] }

// name of all products priced 50 and above
IEnumerable<JToken> pricyProducts = o.SelectTokens("$..Products[?(@.Price >= 50)].Name");

foreach (JToken item in pricyProducts)
{
    Console.WriteLine(item);
}
// Anvil

使用JSON路径和LINQ查询JSON

JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");

string[] storeNames = o.SelectToken("Stores").Select(s => (string)s).ToArray();

Console.WriteLine(string.Join(", ", storeNames));
// Lambton Quay, Willis Street

string[] firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name"))
    .Where(n => n != null).ToArray();

Console.WriteLine(string.Join(", ", firstProductNames));
// Headlight Fluid

decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));

Console.WriteLine(totalPrice);
// 149.95

JSON路径和正则

JArray packages = JArray.Parse(@"[
  {
    'PackageId': 'Newtonsoft.Json',
    'Version': '11.0.1',
    'ReleaseDate': '2018-02-17T00:00:00'
  },
  {
    'PackageId': 'NUnit',
    'Version': '3.9.0',
    'ReleaseDate': '2017-11-10T00:00:00'
  }
]");

// Find Newtonsoft packages
List<JToken> newtonsoftPackages = packages.SelectTokens(@"$.[?(@.PackageId =~ /^Newtonsoft\.(.*)$/)]").ToList();

foreach (JToken item in newtonsoftPackages)
{
    Console.WriteLine((string) item["PackageId"]);
}
// Newtonsoft.Json

JSON路径等于比较操作

JArray items = JArray.Parse(@"[
  {
    'Name': 'Valid JSON',
    'Valid': true
  },
  {
    'Name': 'Invalid JSON',
    'Valid': 'true'
  }
]");

// Use === operator. Compared types must be the same to be valid
List<JToken> strictResults = items.SelectTokens(@"$.[?(@.Valid === true)]").ToList();

foreach (JToken item in strictResults)
{
    Console.WriteLine((string)item["Name"]);
}
// Valid JSON

ToDictionary

 Dictionary<string, string> dictionary = rates.ToDictionary(pair => pair.Key, pair => (string)pair.Value);
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值