您好,欢迎来到华佗小知识。
搜索
您的当前位置:首页Newtonsoft.Json使用方法整理

Newtonsoft.Json使用方法整理

来源:华佗小知识
Newtonsoft.Json使⽤⽅法整理

Newtonsoft.Json使⽤序列化和反序列化JSON使⽤JSON路径查询JSON

使⽤JSON路径和转义属性查询JSON使⽤复杂JSON路径查询JSON使⽤JSON路径和LINQ查询JSONJSON路径和正则

JSON路径等于⽐较操作ToDictionary

序列化和反序列化JSON

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

JsonConvertJson序列化器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\string output = JsonConvert.SerializeObject(product);//{

// \"Name\": \"Apple\

// \"ExpiryDate\": \"2008-12-28T00:00:00\// \"Price\": 3.99,// \"Sizes\": [// \"Small\// \"Medium\// \"Large\"// ]//}

Product deserializedProduct = JsonConvert.DeserializeObject(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\

// name of all products priced 50 and above

IEnumerable 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(\// 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(\// 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 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 strictResults = items.SelectTokens(@\"$.[?(@.Valid === true)]\").ToList();foreach (JToken item in strictResults){

Console.WriteLine((string)item[\"Name\"]);}

// Valid JSON

ToDictionary

Dictionary dictionary = rates.ToDictionary(pair => pair.Key, pair => (string)pair.Value);

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务