Net.Json 常用例子
#JsonConvert 例子
内容主要都是官方的例子,加上一些中文注释而已。 主要方便自己查询,分享一份出来.
参考文档:
https://www.newtonsoft.com/json/help/html/Introduction.htm
##JsonConver序列化
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);
##JsonSerializer
如果需要对对象序列化进行更多的控制。JsonSerializer能够支持Json读写流( JsonTextReader and JsonTextWriter)
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特性
JsonObjectAttribute - 控制Net.Json序列化对象
JsonArrayAttribute - 控制Net.Json序列化Array对象
JsonDictionaryAttribute - 控制Net.Json序列化Dictionary对象
JsonPropertyAttribute - 控制Net.Json这些属性、字段需要序列化
JsonConverterAttribute - 控制classes or fields and properties指定JsonConverter 进行序列化
JsonExtensionDataAttribute - 将不匹配的成员写入指定的容器中,具体可以看例子
JsonConstructorAttribute 指定反序列化时指定构造函数创建类
## Json回调
public class SerializationEventTestObject
{
// 2222
// This member is serialized and deserialized with no change.
public int Member1 { get; set; }
// The value of this field is set and reset during and
// after serialization.
public string Member2 { get; set; }
// This field is not serialized. The OnDeserializedAttribute
// is used to set the member value after serialization.
[JsonIgnore]
public string Member3 { get; set; }
// This field is set to null, but populated after deserialization.
public string Member4 { get; set; }
public SerializationEventTestObject()
{
Member1 = 11;
Member2 = "Hello World!";
Member3 = "This is a nonserialized value";
Member4 = null;
}
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
Member2 = "This value went into the data file during serialization.";
}
[OnSerialized]
internal void OnSerializedMethod(StreamingContext context)
{
Member2 = "This value was reset after serialization.";
}
[OnDeserializing]
internal void OnDeserializingMethod(StreamingContext context)
{
Member3 = "This value was set during deserialization";
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
Member4 = "This value was set after deserialization.";
}
}
###测试代码
SerializationEventTestObject obj = new SerializationEventTestObject();
Console.WriteLine(obj.Member1);
// 11
Console.WriteLine(obj.Member2);
// Hello World!
Console.WriteLine(obj.Member3);
// This is a nonserialized value
Console.WriteLine(obj.Member4);
// null
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
// {
// "Member1": 11,
// "Member2": "This value went into the data file during serialization.",
// "Member4": null
// }
Console.WriteLine(obj.Member1);
// 11
Console.WriteLine(obj.Member2);
// This value was reset after serialization.
Console.WriteLine(obj.Member3);
// This is a nonserialized value
Console.WriteLine(obj.Member4);
// null
obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);
Console.WriteLine(obj.Member1);
// 11
Console.WriteLine(obj.Member2);
// This value went into the data file during serialization.
Console.WriteLine(obj.Member3);
// This value was set during deserialization
Console.WriteLine(obj.Member4);
// This value was set after deserialization.
## Json 错误处理
###方法1 JsonConvert 委托
List<string> errors = new List<string>();
List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[
'2009-09-09T00:00:00Z',
'I am not a date and will error!',
[
1
],
'1977-02-20T00:00:00Z',
null,
'2000-12-01T00:00:00Z'
]",
new JsonSerializerSettings
{
Error = delegate(object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
},
Converters = { new IsoDateTimeConverter() }
});
// 2009-09-09T00:00:00Z
// 1977-02-20T00:00:00Z
// 2000-12-01T00:00:00Z
// The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
// Unexpected token parsing date. Expected String, got StartArray.
// Cannot convert null value to System.DateTime.
###方法2 JsonSerializer 委托
List<string> errors = new List<string>();
JsonSerializer serializer = new JsonSerializer();
serializer.Error += delegate(object sender, ErrorEventArgs args)
{
// only log an error once
if (args.CurrentObject == args.ErrorContext.OriginalObject)
{
errors.Add(args.ErrorContext.Error.Message);
}
};
###方法3 OnErrorAttribute
public class PersonError
{
private List<string> _roles;
public string Name { get; set; }
public int Age { get; set; }
public List<string> Roles
{
get
{
if (_roles == null)
{
throw new Exception("Roles not loaded!");
}
return _roles;
}
set { _roles = value; }
}
public string Title { get; set; }
[OnError]
internal void OnError(StreamingContext context, ErrorContext errorContext)
{
errorContext.Handled = true;
}
}
PersonError person = new PersonError
{
Name = "George Michael Bluth",
Age = 16,
Roles = null,
Title = "Mister Manager"
};
string json = JsonConvert.SerializeObject(person, Formatting.Indented);
Console.WriteLine(json);
//{
// "Name": "George Michael Bluth",
// "Age": 16,
// "Title": "Mister Manager"
//}
## 自定义转换器CustomCreationConverter
public interface IPerson
{
string FirstName { get; set; }
string LastName { get; set; }
DateTime BirthDate { get; set; }
}
public class Employee : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string Department { get; set; }
public string JobTitle { get; set; }
}
public class PersonConverter : CustomCreationConverter<IPerson>
{
public override IPerson Create(Type objectType)
{
return new Employee();
}
}
----------
//[
// {
// "FirstName": "Maurice",
// "LastName": "Moss",
// "BirthDate": "1981-03-08T00:00Z",
// "Department": "IT",
// "JobTitle": "Support"
// },
// {
// "FirstName": "Jen",
// "LastName": "Barber",
// "BirthDate": "1985-12-10T00:00Z",
// "Department": "IT",
// "JobTitle": "Manager"
// }
//]
List<IPerson> people = JsonConvert.DeserializeObject<List<IPerson>>(json, new PersonConverter());
IPerson person = people[0];
Console.WriteLine(person.GetType());
// Newtonsoft.Json.Tests.Employee
Console.WriteLine(person.FirstName);
// Maurice
Employee employee = (Employee)person;
Console.WriteLine(employee.JobTitle);
// Support
## 序列化跟踪日志
Staff staff = new Staff();
staff.Name = "Arnie Admin";
staff.Roles = new List<string> { "Administrator" };
staff.StartDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc);
ITraceWriter traceWriter = new MemoryTraceWriter();
JsonConvert.SerializeObject(
staff,
new JsonSerializerSettings { TraceWriter = traceWriter, Converters = { new JavaScriptDateTimeConverter() } });
Console.WriteLine(traceWriter);
// 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
// 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
// 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
// 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
// 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
// 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
// 2013-05-18T21:38:11.255 Verbose Serialized JSON:
// {
// "Name": "Arnie Admin",
// "StartDate": new Date(
// 976623132000
// ),
// "Roles": [
// "Administrator"
// ]
// }
### 自定义序列化跟踪日志
public class NLogTraceWriter : ITraceWriter
{
private static readonly Logger Logger = LogManager.GetLogger("NLogTraceWriter");
public TraceLevel LevelFilter
{
// trace all messages. nlog can handle filtering
get { return TraceLevel.Verbose; }
}
public void Trace(TraceLevel level, string message, Exception ex)
{
LogEventInfo logEvent = new LogEventInfo
{
Message = message,
Level = GetLogLevel(level),
Exception = ex
};
// log Json.NET message to NLog
Logger.Log(logEvent);
}
private LogLevel GetLogLevel(TraceLevel level)
{
switch (level)
{
case TraceLevel.Error:
return LogLevel.Error;
case TraceLevel.Warning:
return LogLevel.Warn;
case TraceLevel.Info:
return LogLevel.Info;
case TraceLevel.Off:
return LogLevel.Off;
default:
return LogLevel.Trace;
}
}
}
# LINQ to JSON
##解析对象
JObject o = JObject.Parse(@"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive
##解析数组对象
string json = @"[
'Small',
'Medium',
'Large'
]";
JArray a = JArray.Parse(json);
## 创建Json
JArray array = new JArray();
JValue text = new JValue("Manual text");
JValue date = new JValue(new DateTime(2000, 5, 23));
array.Add(text);
array.Add(date);
string json = array.ToString();
// [
// "Manual text",
// "2000-05-23T00:00:00"
// ]
## Linq 创建Json
List<Post> posts = GetPosts();
JObject rss =
new JObject(
new JProperty("channel",
new JObject(
new JProperty("title", "James Newton-King"),
new JProperty("link", "http://james.newtonking.com"),
new JProperty("description", "James Newton-King's blog."),
new JProperty("item",
new JArray(
from p in posts
orderby p.Title
select new JObject(
new JProperty("title", p.Title),
new JProperty("description", p.Description),
new JProperty("link", p.Link),
new JProperty("category",
new JArray(
from c in p.Categories
select new JValue(c)))))))));
Console.WriteLine(rss.ToString());
//{
// "channel": {
// "title": "James Newton-King",
// "link": "http://james.newtonking.com",
// "description": "James Newton-King\'s blog.",
// "item": [
// {
// "title": "Json.NET 1.3 + New license + Now on CodePlex",
// "description": "Annoucing the release of Json.NET 1.3, the MIT license and being available on CodePlex",
// "link": "http://james.newtonking.com/projects/json-net.aspx",
// "category": [
// "Json.NET",
// "CodePlex"
// ]
// },
// {
// "title": "LINQ to JSON beta",
// "description": "Annoucing LINQ to JSON",
// "link": "http://james.newtonking.com/projects/json-net.aspx",
// "category": [
// "Json.NET",
// "LINQ"
// ]
// }
// ]
// }
//}
## 从一个对象创建Json
JObject o = JObject.FromObject(new
{
channel = new
{
title = "James Newton-King",
link = "http://james.newtonking.com",
description = "James Newton-King's blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
## 查询Json值
string json = @"{
'channel': {
'title': 'James Newton-King',
'link': 'http://james.newtonking.com',
'description': 'James Newton-King\'s blog.',
'item': [
{
'title': 'Json.NET 1.3 + New license + Now on CodePlex',
'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'CodePlex'
]
},
{
'title': 'LINQ to JSON beta',
'description': 'Annoucing LINQ to JSON',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'LINQ'
]
}
]
}
}";
JObject rss = JObject.Parse(json);
string rssTitle = (string)rss["channel"]["title"];
// James Newton-King
string itemTitle = (string)rss["channel"]["item"][0]["title"];
// Json.NET 1.3 + New license + Now on CodePlex
JArray categories = (JArray)rss["channel"]["item"][0]["categories"];
// ["Json.NET", "CodePlex"]
IList<string> categoriesText = categories.Select(c => (string)c).ToList();
// Json.NET
// CodePlex
## Linq查询
var postTitles =
from p in rss["channel"]["item"]
select (string)p["title"];
foreach (var item in postTitles)
{
Console.WriteLine(item);
}
//LINQ to JSON beta
//Json.NET 1.3 + New license + Now on CodePlex
var categories =
from c in rss["channel"]["item"].SelectMany(i => i["categories"]).Values<string>()
group c by c
into g
orderby g.Count() descending
select new { Category = g.Key, Count = g.Count() };
foreach (var c in categories)
{
Console.WriteLine(c.Category + " - Count: " + c.Count);
}
//Json.NET - Count: 2
//LINQ - Count: 1
//CodePlex - Count: 1
## 使用LInq反序列化
string jsonText = @"{
'short': {
'original': 'http://www.foo.com/',
'short': 'krehqk',
'error': {
'code': 0,
'msg': 'No action taken'
}
}
}";
JObject json = JObject.Parse(jsonText);
Shortie shortie = new Shortie
{
Original = (string)json["short"]["original"],
Short = (string)json["short"]["short"],
Error = new ShortieException
{
Code = (int)json["short"]["error"]["code"],
ErrorMessage = (string)json["short"]["error"]["msg"]
}
};
Console.WriteLine(shortie.Original);
// http://www.foo.com/
Console.WriteLine(shortie.Error.ErrorMessage);
// No action taken
## SelectToken查询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");
// Acme Co
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
// 50
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
// Elbow Grease
## SelectToken用JsonPath
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
// Elbow Grease
## SelectToken用LINQ
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
// Lambton Quay
// Willis Street
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
// null
// Headlight Fluid
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
// 149.95
#XML转JSON
## SerializeXmlNode
string xml = @"<?xml version='1.0' standalone='no'?>
<root>
<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
</person>
<person id='2'>
<name>Louis</name>
<url>http://www.yahoo.com</url>
</person>
</root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
//{
// "?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"
// }
// ]
// }
//}
## XML属性强制转换为Json
string xml = @"<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role>Admin1</role>
</person>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
//{
// "person": {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com",
// "role": "Admin1"
// }
//}
xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array='true'>Admin</role>
</person>";
doc = new XmlDocument();
doc.LoadXml(xml);
json = JsonConvert.SerializeXmlNode(doc);
//{
// "person": {
// "@id": "1",
// "name": "Alan",
// "url": "http://www.google.com",
// "role": [
// "Admin"
// ]
// }
//}
## JSON转换XML
string 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'
}
]
}
}";
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
// <?xml version="1.0" standalone="no"?>
// <root>
// <person id="1">
// <name>Alan</name>
// <url>http://www.google.com</url>
// </person>
// <person id="2">
// <name>Louis</name>
// <url>http://www.yahoo.com</url>
// </person>
// </root>
Net.Json 常用例子的更多相关文章
- 我教女朋友学编程html系列(7)—Html无序列表、自定义列表、有序列表及常用例子
昨天写的那篇文章<我教女朋友学编程Html系列(6)—Html常用表单控件>,基本上有1000人左右看了,那边文章是我站在前人的肩膀上修改来的,添加了截图和说明,合并了例子,使之更容易被初 ...
- 使用json常用到的包有以下六个
使用json常用到的包有以下六个 1. commons-logging-1.0.4.jar 2. commons-lang-2.3.jar 3. commons-collections-3.2.jar ...
- [svc]sed&awk过滤行及sed常用例子
- sed过滤行 sed '2p' sed '2,5p' sed '2p;3p;4p' - awk过滤行 awk 'NR==2' awk 'NR>=2 && NR <=3' ...
- python实现excel转json的例子
python实现excel转json的例子(改进版) 由于数值策划给出数值是excel表格,但前台flash程序用的又是json格式.服务器也用了json格式,而json又是utf-8编码的,用C++ ...
- 解析3级JSON的例子
我们都知道现在Ajax盛行,而且前后台数据交流的格式已经换成了JSON了.虽然我对这种做法还是有点担忧的,如果用户关闭了JavaScript怎么办?但是这些担忧还是不能阻止Ajax的盛行和JSON数据 ...
- Json常用的转换
简单记录一下jquery里面的JSON.parse()和JSON.stringify()函数,和js中的eval()函数的用法 1,JSON.parse 函数(常用) 作用:将 JavaScript ...
- Json常用序列化工具包大比拼
一.前言 Json已成为计算机编程中最常用的数据传输和存储格式之一,所以对Json的序列化和反序列化工具的选择也是互联网系统中比较重要的环节,尤其在高并发下的执行效率,可能会直接影响系统的吞吐率.本文 ...
- C# 处理 JSON 常用的帮助类
C#请求接口的方法,具体代码: 首先需要添加引用和第三方的组件,具体如下: 引用命名空间: using System.IO; using Newtonsoft.Json.Linq; using Sys ...
- PHP操作redis的常用例子
Redis常用的例子 1,connect 描述:实例连接到一个Redis. 参数:host: string,port: int 返回值:BOOL 成功返回:TRUE;失败返回:FALSE 示例: &l ...
随机推荐
- 多层gmetad配置
经实验表明: ①多层gmetad与ganglia版本无关,且可以多版本兼容 ②多层gmetad只有最底层gmetad能保存详细指标,非底层gmetad收集到的都只能是summary信息,当然也许我配置 ...
- 更简单高效的HTML数据提取-Xpath
XPath 是一门在 XML 文档中查找信息的语言.XPath 用于在 XML 文档中通过元素和属性进行导航. 相比于BeautifulSoup,Xpath在提取数据时会更加的方便. 安装 在Pyth ...
- bootstrap下的双选时间插件使用方法
bootstrap画的页面很漂亮,能自动适应网页端,移动端.实现一个双选时间控件: 要得jar包自己去下 一.页面 二.JS var $createTime=$('#createTime');$cre ...
- spring boot开发REST接口
1.配置pom.xml文件的<parent>和<depencencies>,指定spring boot web依赖 <parent> <groupId> ...
- 64位CentOS6.5下Eclipse用Java连接mysql
1.到官网上下载jdbc驱动,我下载的是mysql-connector-java-5.0.8.tar.gz 2.解压下载到的文件 tar -zxvf mysql-connector-java-5.0. ...
- CODEVS——T 1049 棋盘染色
http://codevs.cn/problem/1049/ 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold 题解 查看运行结果 题目描述 Descr ...
- keras 与tensorflow 混合使用
keras 与tensorflow 混合使用 tr:nth-child(odd) > td, .table-striped tbody > tr:nth-child(odd) > t ...
- Axure RP一个专业的高速原型设计工具
Axure RP是一个专业的高速原型设计工具.Axure(发音:Ack-sure),代表美国Axure公司.RP则是Rapid Prototyping(高速原型)的缩写. Axure简要介绍 Axur ...
- 浏览器最小字体小于12px解决方案
<style> p{font-size:10px;-webkit-transform:scale(0.8);} /*这里的数字0.8,是缩放比例,可以根据情况变化.*/ </styl ...
- 第十七周自由练习项目——acm 学生最高最低成绩
/* *程序的版权和版本号声明部分: *Copyright(c)2014,烟台大学计算机学院学生 *All rights reserved. *文件名:acm 学生最高与最低成绩 *作者:刘中林 *完 ...