(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);