这次给大家带来使用json.net的方法,使用json.net的方法的注意事项有哪些,下面就是实战案例,一起来看一下。
json.net 常用使用小结(推荐)
using system;
using system.linq;
using system.collections.generic;
namespace microstore
{
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 : newtonsoft.json.converters.customcreationconverter<iperson>
{
//重写abstract class customcreationconverter<t>的create方法
public override iperson create(type objecttype)
{
return new employee();
}
}
public partial class testjson : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
//if (!ispostback)
// testjson();
}
#region 序列化
public string testjsonserialize()
{
product product = new product();
product.name = apple;
product.expiry = datetime.now.adddays(3).tostring(yyyy-mm-dd hh:mm:ss);
product.price = 3.99m;
//product.sizes = new string[] { small, medium, large };
//string json = newtonsoft.json.jsonconvert.serializeobject(product); //没有缩进输出
string json = newtonsoft.json.jsonconvert.serializeobject(product, newtonsoft.json.formatting.indented);
//string json = newtonsoft.json.jsonconvert.serializeobject(
// product,
// newtonsoft.json.formatting.indented,
// new newtonsoft.json.jsonserializersettings { nullvaluehandling = newtonsoft.json.nullvaluehandling.ignore }
//);
return string.format(<p>{0}</p>, json);
}
public string testlistjsonserialize()
{
product product = new product();
product.name = apple;
product.expiry = datetime.now.adddays(3).tostring(yyyy-mm-dd hh:mm:ss);
product.price = 3.99m;
product.sizes = new string[] { small, medium, large };
list<product> plist = new list<product>();
plist.add(product);
plist.add(product);
string json = newtonsoft.json.jsonconvert.serializeobject(plist, newtonsoft.json.formatting.indented);
return string.format(<p>{0}</p>, json);
}
#endregion
#region 反序列化
public string testjsondeserialize()
{
string strjson = {\name\:\apple\,\expiry\:\2014-05-03 10:20:59\,\price\:3.99,\sizes\:[\small\,\medium\,\large\]};
product p = newtonsoft.json.jsonconvert.deserializeobject<product>(strjson);
string template = @<p><ul>
<li>{0}</li>
<li>{1}</li>
<li>{2}</li>
<li>{3}</li>
</ul></p>;
return string.format(template, p.name, p.expiry, p.price.tostring(), string.join(,, p.sizes));
}
public string testlistjsondeserialize()
{
string strjson = {\name\:\apple\,\expiry\:\2014-05-03 10:20:59\,\price\:3.99,\sizes\:[\small\,\medium\,\large\]};
list<product> plist = newtonsoft.json.jsonconvert.deserializeobject(string.format([{0},{1}], strjson, strjson));
string template = @<p><ul>
<li>{0}</li>
<li>{1}</li>
<li>{2}</li>
<li>{3}</li>
</ul></p>;
system.text.stringbuilder strb = new system.text.stringbuilder();
plist.foreach(x =>
strb.appendline(
string.format(template, x.name, x.expiry, x.price.tostring(), string.join(,, x.sizes))
)
);
return strb.tostring();
}
#endregion
#region 自定义反序列化
public string testlistcustomdeserialize()
{
string strjson = [ { \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 = newtonsoft.json.jsonconvert.deserializeobject(strjson, new personconverter());
iperson person = people[0];
string template = @<p><ul>
<li>当前list<iperson>[x]对象类型:{0}</li>
<li>firstname:{1}</li>
<li>lastname:{2}</li>
<li>birthdate:{3}</li>
<li>department:{4}</li>
<li>jobtitle:{5}</li>
</ul></p>;
system.text.stringbuilder strb = new system.text.stringbuilder();
people.foreach(x =>
strb.appendline(
string.format(
template,
person.gettype().tostring(),
x.firstname,
x.lastname,
x.birthdate.tostring(),
((employee)x).department,
((employee)x).jobtitle
)
)
);
return strb.tostring();
}
#endregion
#region 反序列化成dictionary
public string testdeserialize2dic()
{
//string json = @{key1:zhangsan,key2:lisi};
//string json = {\key1\:\zhangsan\,\key2\:\lisi\};
string json = {key1:\zhangsan\,key2:\lisi\};
dictionary<string, string> dic = newtonsoft.json.jsonconvert.deserializeobject(json);
string template = @<li>key:{0},value:{1}</li>;
system.text.stringbuilder strb = new system.text.stringbuilder();
strb.append(dictionary<string, string>长度 + dic.count.tostring() + <ul>);
dic.asqueryable().tolist().foreach(x =>
{
strb.appendline(string.format(template, x.key, x.value));
});
strb.append(</ul>);
return strb.tostring();
}
#endregion
#region nullvaluehandling特性
public class movie
{
public string name { get; set; }
public string description { get; set; }
public string classification { get; set; }
public string studio { get; set; }
public datetime? releasedate { get; set; }
public list<string> releasecountries { get; set; }
}
/// <summary>
/// 完整序列化输出
/// </summary>
public string commonserialize()
{
movie movie = new movie();
movie.name = bad boys iii;
movie.description = it's no bad boys;
string included = newtonsoft.json.jsonconvert.serializeobject(
movie,
newtonsoft.json.formatting.indented, //缩进
new newtonsoft.json.jsonserializersettings { }
);
return included;
}
/// <summary>
/// 忽略空(null)对象输出
/// </summary>
/// <returns></returns>
public string ignoredserialize()
{
movie movie = new movie();
movie.name = bad boys iii;
movie.description = it's no bad boys;
string included = newtonsoft.json.jsonconvert.serializeobject(
movie,
newtonsoft.json.formatting.indented, //缩进
new newtonsoft.json.jsonserializersettings { nullvaluehandling = newtonsoft.json.nullvaluehandling.ignore }
);
return included;
}
#endregion
public class product
{
public string name { get; set; }
public string expiry { get; set; }
public decimal price { get; set; }
public string[] sizes { get; set; }
}
#region defaultvaluehandling默认值
public class invoice
{
public string company { get; set; }
public decimal amount { get; set; }
// false is default value of bool
public bool paid { get; set; }
// null is default value of nullable
public datetime? paiddate { get; set; }
// customize default values
[system.componentmodel.defaultvalue(30)]
public int followupdays { get; set; }
[system.componentmodel.defaultvalue()]
public string followupemailaddress { get; set; }
}
public void gg()
{
invoice invoice = new invoice
{
company = acme ltd.,
amount = 50.0m,
paid = false,
followupdays = 30,
followupemailaddress = string.empty,
paiddate = null
};
string included = newtonsoft.json.jsonconvert.serializeobject(
invoice,
newtonsoft.json.formatting.indented,
new newtonsoft.json.jsonserializersettings { }
);
// {
// company: acme ltd.,
// amount: 50.0,
// paid: false,
// paiddate: null,
// followupdays: 30,
// followupemailaddress:
// }
string ignored = newtonsoft.json.jsonconvert.serializeobject(
invoice,
newtonsoft.json.formatting.indented,
new newtonsoft.json.jsonserializersettings { defaultvaluehandling = newtonsoft.json.defaultvaluehandling.ignore }
);
// {
// company: acme ltd.,
// amount: 50.0
// }
}
#endregion
#region jsonignoreattribute and datamemberattribute 特性
public string outincluded()
{
car car = new car
{
model = zhangsan,
year = datetime.now,
features = new list<string> { aaaa, bbbb, cccc },
lastmodified = datetime.now.adddays(5)
};
return newtonsoft.json.jsonconvert.serializeobject(car, newtonsoft.json.formatting.indented);
}
public string outincluded2()
{
computer com = new computer
{
name = zhangsan,
saleprice = 3999m,
manufacture = red,
stockcount = 5,
wholesaleprice = 34m,
nextshipmentdate = datetime.now.adddays(5)
};
return newtonsoft.json.jsonconvert.serializeobject(com, newtonsoft.json.formatting.indented);
}
public class car
{
// included in json
public string model { get; set; }
public datetime year { get; set; }
public list<string> features { get; set; }
// ignored
[newtonsoft.json.jsonignore]
public datetime lastmodified { get; set; }
}
//在nt3.5中需要添加system.runtime.serialization.dll引用
[system.runtime.serialization.datacontract]
public class computer
{
// included in json
[system.runtime.serialization.datamember]
public string name { get; set; }
[system.runtime.serialization.datamember]
public decimal saleprice { get; set; }
// ignored
public string manufacture { get; set; }
public int stockcount { get; set; }
public decimal wholesaleprice { get; set; }
public datetime nextshipmentdate { get; set; }
}
#endregion
#region icontractresolver特性
public class book
{
public string bookname { get; set; }
public decimal bookprice { get; set; }
public string authorname { get; set; }
public int authorage { get; set; }
public string authorcountry { get; set; }
}
public void kk()
{
book book = new book
{
bookname = the gathering storm,
bookprice = 16.19m,
authorname = brandon sanderson,
authorage = 34,
authorcountry = united states of america
};
string startingwitha = newtonsoft.json.jsonconvert.serializeobject(
book, newtonsoft.json.formatting.indented,
new newtonsoft.json.jsonserializersettings { contractresolver = new dynamiccontractresolver('a') }
);
// {
// authorname: brandon sanderson,
// authorage: 34,
// authorcountry: united states of america
// }
string startingwithb = newtonsoft.json.jsonconvert.serializeobject(
book,
newtonsoft.json.formatting.indented,
new newtonsoft.json.jsonserializersettings { contractresolver = new dynamiccontractresolver('b') }
);
// {
// bookname: the gathering storm,
// bookprice: 16.19
// }
}
public class dynamiccontractresolver : newtonsoft.json.serialization.defaultcontractresolver
{
private readonly char _startingwithchar;
public dynamiccontractresolver(char startingwithchar)
{
_startingwithchar = startingwithchar;
}
protected override ilist<newtonsoft.json.serialization.jsonproperty> createproperties(type type, newtonsoft.json.memberserialization memberserialization)
{
ilist<newtonsoft.json.serialization.jsonproperty> properties = base.createproperties(type, memberserialization);
// only serializer properties that start with the specified character
properties =
properties.where(p => p.propertyname.startswith(_startingwithchar.tostring())).tolist();
return properties;
}
}
#endregion
//...
}
}
#region serializing partial json fragment example
public class searchresult
{
public string title { get; set; }
public string content { get; set; }
public string url { get; set; }
}
public string serializingjsonfragment()
{
#region
string googlesearchtext = @{
'responsedata': {
'results': [{
'gsearchresultclass': 'gwebsearch',
'unescapedurl': 'http://en.wikipedia.org/wiki/paris_hilton',
'url': 'http://en.wikipedia.org/wiki/paris_hilton',
'visibleurl': 'en.wikipedia.org',
'cacheurl': 'http://www.google.com/search?q=cache:twrpfhd22hyj:en.wikipedia.org',
'title': '<b>paris hilton</b> - wikipedia, the free encyclopedia',
'titlenoformatting': 'paris hilton - wikipedia, the free encyclopedia',
'content': '[1] in 2006, she released her debut album...'
},
{
'gsearchresultclass': 'gwebsearch',
'unescapedurl': 'http://www.imdb.com/name/nm0385296/',
'url': 'http://www.imdb.com/name/nm0385296/',
'visibleurl': 'www.imdb.com',
'cacheurl': 'http://www.google.com/search?q=cache:1i34kkqnsooj:www.imdb.com',
'title': '<b>paris hilton</b>',
'titlenoformatting': 'paris hilton',
'content': 'self: zoolander. socialite <b>paris hilton</b>...'
}],
'cursor': {
'pages': [{
'start': '0',
'label': 1
},
{
'start': '4',
'label': 2
},
{
'start': '8',
'label': 3
},
{
'start': '12',
'label': 4
}],
'estimatedresultcount': '59600000',
'currentpageindex': 0,
'moreresultsurl': 'http://www.google.com/search?oe=utf8&ie=utf8...'
}
},
'responsedetails': null,
'responsestatus': 200
};
#endregion
newtonsoft.json.linq.jobject googlesearch = newtonsoft.json.linq.jobject.parse(googlesearchtext);
// get json result objects into a list
list<newtonsoft.json.linq.jtoken> listjtoken = googlesearch[responsedata][results].children().tolist();
system.text.stringbuilder strb = new system.text.stringbuilder();
string template = @<ul>
<li>title:{0}</li>
<li>content: {1}</li>
<li>url:{2}</li>
</ul>;
listjtoken.foreach(x =>
{
// serialize json results into .net objects
searchresult searchresult = newtonsoft.json.jsonconvert.deserializeobject<searchresult>(x.tostring());
strb.appendline(string.format(template, searchresult.title, searchresult.content, searchresult.url));
});
return strb.tostring();
}
#endregion
#region shouldserialize
public class cc
{
public string name { get; set; }
public cc manager { get; set; }
//http://msdn.microsoft.com/en-us/library/53b8022e.aspx
public bool shouldserializemanager()
{
// don't serialize the manager property if an employee is their own manager
return (manager != this);
}
}
public string shouldserializetest()
{
//create employee mike
cc mike = new cc();
mike.name = mike manager;
//create employee joe
cc joe = new cc();
joe.name = joe employee;
joe.manager = mike; //set joe'manager = mike
// mike is his own manager
// shouldserialize will skip this property
mike.manager = mike;
return newtonsoft.json.jsonconvert.serializeobject(new[] { joe, mike }, newtonsoft.json.formatting.indented);
}
#endregion
//驼峰结构输出(小写打头,后面单词大写)
public string jjj()
{
product product = new product
{
name = widget,
expiry = datetime.now.tostring(),
price = 9.99m,
sizes = new[] { small, medium, large }
};
string json = newtonsoft.json.jsonconvert.serializeobject(
product,
newtonsoft.json.formatting.indented,
new newtonsoft.json.jsonserializersettings { contractresolver = new newtonsoft.json.serialization.camelcasepropertynamescontractresolver() }
);
return json;
//{
// name: widget,
// expirydate: 2010-12-20t18:01z,
// price: 9.99,
// sizes: [
// small,
// medium,
// large
// ]
//}
}
#region itracewriter
public class staff
{
public string name { get; set; }
public list<string> roles { get; set; }
public datetime startdate { get; set; }
}
public void kkkk()
{
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);
newtonsoft.json.serialization.itracewriter tracewriter = new newtonsoft.json.serialization.memorytracewriter();
newtonsoft.json.jsonconvert.serializeobject(
staff,
new newtonsoft.json.jsonserializersettings
{
tracewriter = tracewriter,
converters = { new newtonsoft.json.converters.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
// ]
// }
}
#endregion
public string testreadjsonfromfile()
{
linq2json l2j = new linq2json();
newtonsoft.json.linq.jobject jarray = l2j.getjobject4();
return jarray.tostring();
}
using system;
using system.collections.generic;
using system.linq;
using system.web;
namespace microstore
{
public class linq2json
{
#region getjobject
//parsing a json object from text
public newtonsoft.json.linq.jobject getjobject()
{
string json = @{
cpu: 'intel',
drives: [
'dvd read/writer',
'500 gigabyte hard drive'
]
};
newtonsoft.json.linq.jobject jobject = newtonsoft.json.linq.jobject.parse(json);
return jobject;
}
/*
* //example:=>
*
linq2json l2j = new linq2json();
newtonsoft.json.linq.jobject jobject = l2j.getjobject2(server.mappath(json/person.json));
//return newtonsoft.json.jsonconvert.serializeobject(jobject, newtonsoft.json.formatting.indented);
return jobject.tostring();
*/
//loading json from a file
public newtonsoft.json.linq.jobject getjobject2(string jsonpath)
{
using (system.io.streamreader reader = system.io.file.opentext(jsonpath))
{
newtonsoft.json.linq.jobject jobject = (newtonsoft.json.linq.jobject)newtonsoft.json.linq.jtoken.readfrom(new newtonsoft.json.jsontextreader(reader));
return jobject;
}
}
//creating jobject
public newtonsoft.json.linq.jobject getjobject3()
{
list<post> posts = getposts();
newtonsoft.json.linq.jobject jobject = newtonsoft.json.linq.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.category
}
}
});
return jobject;
}
/*
{
channel: {
title: james newton-king,
link: http://james.newtonking.com,
description: james newton-king's blog.,
item: [{
title: jewron,
description: 4546fds,
link: http://www.baidu.com,
category: jhgj
},
{
title: jofdsn,
description: mdsfan,
link: http://www.baidu.com,
category: 6546
},
{
title: jokjn,
description: m3214an,
link: http://www.baidu.com,
category: hg425
},
{
title: jon,
description: man,
link: http://www.baidu.com,
category: goodman
}]
}
}
*/
//creating jobject
public newtonsoft.json.linq.jobject getjobject4()
{
list<post> posts = getposts();
newtonsoft.json.linq.jobject rss = new newtonsoft.json.linq.jobject(
new newtonsoft.json.linq.jproperty(channel,
new newtonsoft.json.linq.jobject(
new newtonsoft.json.linq.jproperty(title, james newton-king),
new newtonsoft.json.linq.jproperty(link, http://james.newtonking.com),
new newtonsoft.json.linq.jproperty(description, james newton-king's blog.),
new newtonsoft.json.linq.jproperty(item,
new newtonsoft.json.linq.jarray(
from p in posts
orderby p.title
select new newtonsoft.json.linq.jobject(
new newtonsoft.json.linq.jproperty(title, p.title),
new newtonsoft.json.linq.jproperty(description, p.description),
new newtonsoft.json.linq.jproperty(link, p.link),
new newtonsoft.json.linq.jproperty(category,
new newtonsoft.json.linq.jarray(
from c in p.category
select new newtonsoft.json.linq.jvalue(c)
)
)
)
)
)
)
)
);
return rss;
}
/*
{
channel: {
title: james newton-king,
link: http://james.newtonking.com,
description: james newton-king's blog.,
item: [{
title: jewron,
description: 4546fds,
link: http://www.baidu.com,
category: [j, h, g, j]
},
{
title: jofdsn,
description: mdsfan,
link: http://www.baidu.com,
category: [6, 5, 4, 6]
},
{
title: jokjn,
description: m3214an,
link: http://www.baidu.com,
category: [h, g, 4, 2, 5]
},
{
title: jon,
description: man,
link: http://www.baidu.com,
category: [g, o, o, d, m, a, n]
}]
}
}
*/
public class post
{
public string title { get; set; }
public string description { get; set; }
public string link { get; set; }
public string category { get; set; }
}
private list<post> getposts()
{
list<post> listp = new list<post>()
{
new post{title=jon,description=man,link=http://www.baidu.com,category=goodman},
new post{title=jofdsn,description=mdsfan,link=http://www.baidu.com,category=6546},
new post{title=jewron,description=4546fds,link=http://www.baidu.com,category=jhgj},
new post{title=jokjn,description=m3214an,link=http://www.baidu.com,category=hg425}
};
return listp;
}
#endregion
#region getjarray
/*
* //example:=>
*
linq2json l2j = new linq2json();
newtonsoft.json.linq.jarray jarray = l2j.getjarray();
return newtonsoft.json.jsonconvert.serializeobject(jarray, newtonsoft.json.formatting.indented);
//return jarray.tostring();
*/
//parsing a json array from text
public newtonsoft.json.linq.jarray getjarray()
{
string json = @[
'small',
'medium',
'large'
];
newtonsoft.json.linq.jarray jarray = newtonsoft.json.linq.jarray.parse(json);
return jarray;
}
//creating jarray
public newtonsoft.json.linq.jarray getjarray2()
{
newtonsoft.json.linq.jarray array = new newtonsoft.json.linq.jarray();
newtonsoft.json.linq.jvalue text = new newtonsoft.json.linq.jvalue(manual text);
newtonsoft.json.linq.jvalue date = new newtonsoft.json.linq.jvalue(new datetime(2000, 5, 23));
//add to jarray
array.add(text);
array.add(date);
return array;
}
#endregion
//待续...
}
}
测试效果:
<%@ page language="c#" autoeventwireup="true" codebehind="testjson.aspx.cs" inherits="microstore.testjson" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<style type="text/css">
body{ font-family:arial,微软雅黑; font-size:14px;}
a{ text-decoration:none; color:#333;}
a:hover{ text-decoration:none; color:#f00;}
</style>
</head>
<body>
<form id="form1" runat="server">
<h3>序列化对象</h3>
表现1:<br />
<%=testjsonserialize()%>
<%=testlistjsonserialize() %>
表现2:<br />
<%=testlistjsonserialize2() %>
<hr />
<h3>反序列化对象</h3>
<p>单个对象</p>
<%=testjsondeserialize() %>
<p>多个对象</p>
<%=testlistjsondeserialize() %>
<p>反序列化成数据字典dictionary</p>
<%=testdeserialize2dic() %>
<hr />
<h3>自定义反序列化</h3>
<%=testlistcustomdeserialize()%>
<hr />
<h3>序列化输出的忽略特性</h3>
nullvaluehandling特性忽略=><br />
<%=commonserialize() %><br />
<%=ignoredserialize()%><br /><br />
属性标记忽略=><br />
<%=outincluded() %><br />
<%=outincluded2() %>
<hr />
<h3>serializing partial json fragments</h3>
<%=serializingjsonfragment() %>
<hr />
<h3>shouldserialize</h3>
<%=shouldserializetest() %><br />
<%=jjj() %><br /><br />
<%=testreadjsonfromfile() %>
</form>
</body>
</html>
显示:
序列化对象
表现1:
{ name: apple, expiry: 2014-05-04 02:08:58, price: 3.99, sizes: null }
[ { name: apple, expiry: 2014-05-04 02:08:58, price: 3.99, sizes: [ small, medium, large ] }, { name: apple, expiry: 2014-05-04 02:08:58, price: 3.99, sizes: [ small, medium, large ] } ]
表现2:
[ { name: apple, expiry: 2014-05-04 02:08:58, price: 3.99, sizes: [ small, medium, large ] }, { name: apple, expiry: 2014-05-04 02:08:58, price: 3.99, sizes: [ small, medium, large ] } ]
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
ajax获得json数据后格式怎么转换
ajax三种解析模式使用详解
以上就是使用json.net的方法的详细内容。