JSON.NET Doc 摘录
Json.NET Documentation -- 摘录
网址:https://www.newtonsoft.com/json/help/html/Samples.htm
目录:
Samples
- Serializing JSON - 序列化和反序列化 JSON、序列化器设置和序列化属性
- LINQ to JSON - 解析、查询、修改和编写 JSON
- JSON Schema - 加载模式并验证 JSON。请注意,JSON 模式验证已移至其自己的包中。有关 更多详细信息,请参阅https://www.newtonsoft.com/jsonschema。
- 转换 XML - 将 JSON 转换为 XML 和将 XML转换为 JSON
- BSON - 序列化和反序列化 BSON
- 读取和写入 JSON - 使用 JsonTextReader 读取 JSON,使用 JsonTextWriter 写入 JSON
Serializing JSON
序列化对象
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList Roles { get; set; }
}
Account account = new Account
{
Email = "james@example.com",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List
{
"User",
"Admin"
}
};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
// {
// "Email": "james@example.com",
// "Active": true,
// "CreatedDate": "2013-01-20T00:00:00Z",
// "Roles": [
// "User",
// "Admin"
// ]
// }
Console.WriteLine(json);
序列化字典
Dictionary points = new Dictionary
{
{ "James", 9001 },
{ "Jo", 3474 },
{ "Jess", 11926 }
};
string json = JsonConvert.SerializeObject(points, Formatting.Indented);
Console.WriteLine(json);
// {
// "James": 9001,
// "Jo": 3474,
// "Jess": 11926
// }
序列化集合
List videogames = new List
{
"Starcraft",
"Halo",
"Legend of Zelda"
};
string json = JsonConvert.SerializeObject(videogames);
Console.WriteLine(json);
// ["Starcraft","Halo","Legend of Zelda"]
将 JSON 序列化为文件
public class Movie
{
public string Name { get; set; }
public int Year { get; set; }
}
Movie movie = new Movie
{
Name = "Bad Boys",
Year = 1995
};
// serialize JSON to a string and then write string to a file
File.WriteAllText(@"c:\movie.json", JsonConvert.SerializeObject(movie));
// serialize JSON directly to a file
using (StreamWriter file = File.CreateText(@"c:\movie.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, movie);
}
Deserialize to JSON
反序列化对象
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList Roles { get; set; }
}
string json = @"{
'Email': 'james@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject(json);
Console.WriteLine(account.Email);
// james@example.com
反序列化集合
string json = @"['Starcraft','Halo','Legend of Zelda']";List videogames = JsonConvert.DeserializeObject>(json);Console.WriteLine(string.Join(", ", videogames.ToArray()));// Starcraft, Halo, Legend of Zelda
序列化字典
string json = @"{
'href': '/account/login.aspx',
'target': '_blank'
}";
Dictionary htmlAttributes = JsonConvert.DeserializeObject>(json);
Console.WriteLine(htmlAttributes["href"]);
// /account/login.aspx
Console.WriteLine(htmlAttributes["target"]);
// _blank
反序列化匿名类型
var definition = new { Name = "" };
string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
Console.WriteLine(customer1.Name);
// James
string json2 = @"{'Name':'Mike'}";
var customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);
Console.WriteLine(customer2.Name);
// Mike
从文件反序列化 JSON
{
public string Name { get; set; }
public int Year { get; set; }
}
// read file into a string and deserialize JSON to a type
Movie movie1 = JsonConvert.DeserializeObject(File.ReadAllText(@"c:\movie.json"));
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\movie.json"))
{
JsonSerializer serializer = new JsonSerializer();
Movie movie2 = (Movie)serializer.Deserialize(file, typeof(Movie));
}
Convert JSON to XML
将 JSON 转换为 XML
string json = @"{
'@Id': 1,
'Email': 'james@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
],
'Team': {
'@Id': 2,
'Name': 'Software Developers',
'Description': 'Creators of fine software products and services.'
}
}";
XNode node = JsonConvert.DeserializeXNode(json, "Root");
Console.WriteLine(node.ToString());
//
// james@example.com
// true
// 2013-01-20T00:00:00Z
// User
// Admin
//
// Software Developers
// Creators of fine software products and services.
//
//
将XML 转换为JSON
string xml = @"<?xml version='1.0' standalone='no'?>
Alan
http://www.google.com
Louis
http://www.yahoo.com
";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
Console.WriteLine(json);
// {
// "?xml": {
// "@version": "1.0",
// "@standalone": "no"
// },
// "root": {
// "person": [
// {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com"
// },
// {
// "@id": "2",
// "name": "Louis",
// "url": "http://www.yahoo.com"
// }
// ]
// }
// }
LINQ to JSON
手动创建 JSON
JArray array = new JArray();
array.Add("Manual text");
array.Add(new DateTime(2000, 5, 23));
JObject o = new JObject();
o["MyArray"] = array;
string json = o.ToString();
// {
// "MyArray": [
// "Manual text",
// "2000-05-23T00:00:00"
// ]
// }
使用集合创建 JSON
JObject o = new JObject
{
{ "Cpu", "Intel" },
{ "Memory", 32 },
{
"Drives", new JArray
{
"DVD",
"SSD"
}
}
};
Console.WriteLine(o.ToString());
// {
// "Cpu": "Intel",
// "Memory": 32,
// "Drives": [
// "DVD",
// "SSD"
// ]
// }
使用 JTokenWriter 创建 JSON
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("name1");
writer.WriteValue("value1");
writer.WritePropertyName("name2");
writer.WriteStartArray();
writer.WriteValue(1);
writer.WriteValue(2);
writer.WriteEndArray();
writer.WriteEndObject();
JObject o = (JObject)writer.Token;
Console.WriteLine(o.ToString());
// {
// "name1": "value1",
// "name2": [
// 1,
// 2
// ]
// }
从对象创建 JSON
Computer computer = new Computer
{
Cpu = "Intel",
Memory = 32,
Drives = new List
{
"DVD",
"SSD"
}
};
JObject o = (JObject)JToken.FromObject(computer);
Console.WriteLine(o.ToString());
// {
// "Cpu": "Intel",
// "Memory": 32,
// "Drives": [
// "DVD",
// "SSD"
// ]
// }
JArray a = (JArray)JToken.FromObject(computer.Drives);
Console.WriteLine(a.ToString());
// [
// "DVD",
// "SSD"
// ]
public class Computer
{
public string Cpu { get; set; }
public int Memory { get; set; }
public IList Drives { get; set; }
}
使用 JObject.Parse 解析 JSON 对象
string json = @"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
Console.WriteLine(o.ToString());
// {
// "CPU": "Intel",
// "Drives": [
// "DVD read/writer",
// "500 gigabyte hard drive"
// ]
// }
从文件中读取 JSON
JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject)JToken.ReadFrom(reader);
}
将 JSON 写入文件
JObject videogameRatings = new JObject(
new JProperty( "Halo" , 9 ),
new JProperty( "Starcraft" , 9 ),
new JProperty( "Call of Duty" , 7.5 ));
File.WriteAllText( @"c:\videogames.json" , videogameRatings.ToString());
// 将 JSON 直接写入文件
using (StreamWriter file = File.CreateText( @"c:\videogames.json" ))
using (JsonTextWriter writer = new JsonTextWriter(file))
{
videogameRatings.WriteTo(writer);
}
将 JSON 转换为集合
string json = @"{
'd': [
{
'Name': 'John Smith'
},
{
'Name': 'Mike Smith'
}
]
}";
JObject o = JObject.Parse(json);
JArray a = (JArray)o["d"];
IList person = a.ToObject>();
Console.WriteLine(person[0].Name);
// John Smith
Console.WriteLine(person[1].Name);
// Mike Smith
使用 JObject.Properties
JObject o = new JObject
{
{ "name1", "value1" },
{ "name2", "value2" }
};
foreach (JProperty property in o.Properties())
{
Console.WriteLine(property.Name + " - " + property.Value);
}
// name1 - value1
// name2 - value2
foreach (KeyValuePair property in o)
{
Console.WriteLine(property.Key + " - " + property.Value);
}
// name1 - value1
// name2 - value2
使用 JToken.ToString 写入 JSON 文本
JObject o = JObject.Parse( @"{'string1':'value','integer2':99,'datetime3':'2000-05-23T00:00:00'}" );
Console.WriteLine(o.ToString());
// {
// "string1": "value",
// "integer2": 99,
// "datetime3": "2000-05-23T00:00:00"
// }
Console.WriteLine(o.ToString(Formatting.None));
// {"string1":"value","integer2":99,"datetime3":"2000-05-23T00:00:00"}
Console.WriteLine(o.ToString(Formatting.None, new JavaScriptDateTimeConverter()));
// {"string1":"value","integer2":99,"datetime3":new Date(959032800000)}
JSON Path
使用 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 pricyProducts = o.SelectTokens("$..Products[?(@.Price >= 50)].Name");
foreach (JToken item in pricyProducts)
{
Console.WriteLine(item);
}
// Anvil
// Elbow Grease
使用 JSON 路径和 LINQ 查询 JSON
此示例加载 JSON,然后使用SelectToken(String) 和 LINQ 运算符的组合从中查询值。
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 items = JArray.Parse(@"[
{
'Name': 'John Doe',
},
{
'Name': 'Jane Doe',
}
]");
// A true value for errorWhenNoMatch will result in an error if the queried value is missing
string result;
try
{
result = (string)items.SelectToken(@"$.[3]['Name']", errorWhenNoMatch: true);
}
catch (JsonException)
{
result = "Unable to find result in JSON.";
}
读取和写入 JSON
使用 JsonTextReader 读取 JSON
string json = @"{
'CPU': 'Intel',
'PSU': '500W',
'Drives': [
'DVD read/writer'
/*(broken)*/,
'500 gigabyte hard drive',
'200 gigabyte hard drive'
]
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
if (reader.Value != null)
{
Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
}
else
{
Console.WriteLine("Token: {0}", reader.TokenType);
}
}
// Token: StartObject
// Token: PropertyName, Value: CPU
// Token: String, Value: Intel
// Token: PropertyName, Value: PSU
// Token: String, Value: 500W
// Token: PropertyName, Value: Drives
// Token: StartArray
// Token: String, Value: DVD read/writer
// Token: Comment, Value: (broken)
// Token: String, Value: 500 gigabyte hard drive
// Token: String, Value: 200 gigabyte hard drive
// Token: EndArray
// Token: EndObject
使用 JsonTextWriter 编写 JSON
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("CPU");
writer.WriteValue("Intel");
writer.WritePropertyName("PSU");
writer.WriteValue("500W");
writer.WritePropertyName("Drives");
writer.WriteStartArray();
writer.WriteValue("DVD read/writer");
writer.WriteComment("(broken)");
writer.WriteValue("500 gigabyte hard drive");
writer.WriteValue("200 gigabyte hard drive");
writer.WriteEnd();
writer.WriteEndObject();
}
Console.WriteLine(sb.ToString());
// {
// "CPU": "Intel",
// "PSU": "500W",
// "Drives": [
// "DVD read/writer"
// /*(broken)*/,
// "500 gigabyte hard drive",
// "200 gigabyte hard drive"
// ]
// }