在JSON文本和.NET对象之间转换的最快方法是使用Json序列化器…JsonSeriizer通过将.NET对象属性名称映射到JSON属性名称,并为您复制值,将.NET对象转换为其等效的JSON并再次返回。
用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}
}
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
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
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
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
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
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
Dictionary<string, string> dictionary = rates.ToDictionary(pair => pair.Key, pair => (string)pair.Value);