Sunteți pe pagina 1din 24

http://james.newtonking.com/json/help/index.

html
LINQ to JSON
LINQ to JSON is an API o! wo!king with JSON o"jects. It has "een designed with LINQ in mind to ena"le to #$ick
#$e!%ing and c!eation o JSON o"jects. LINQ to JSON sits $nde! the Newtonsot.Json.Lin# namespace
Using LINQ for JSON
JObject o = JObject.Parse(@"{
'CPU' 'Inte!'"
'#ri$es' %
'#&# rea'()riter'"
'*++ gigab,te -ar' 'ri$e'
.
/"01
string c23 = (string0o%"CPU".1
(( Inte!
string first#ri$e = (string0o%"#ri$es".%+.1
(( #&# rea'()riter
IList4string5 a!!#ri$es = o%"#ri$es"..Se!ect(t =5 (string0t0.6oList(01
(( #&# rea'()riter
(( *++ gigab,te -ar' 'ri$e
Pa!sing JSON
LINQ to JSON has methods a&aila"le o! pa!sing JSON !om a st!ing o! loading JSON di!ectl% !om a ile
Parsing JSON text
JSON &al$es can "e !ead !om a st!ing $sing Pa!se'St!ing(.
Pa!sing a JSON O"ject !om text
string json = @"{
CPU 'Inte!'"
#ri$es %
'#&# rea'()riter'"
'*++ gigab,te -ar' 'ri$e'
.
/"1
JObject o = JObject.Parse(json01
Pa!sing a JSON A!!a% !om text
string json = @"%
'S7a!!'"
'8e'i37'"
'Large'
."1
J9rra, a = J9rra,.Parse(json01
Loading JSON from a file
JSON can also "e loaded di!ectl% !om a ile $sing )ead*!om'Json)eade!(.
)eading JSON !om a ile
3sing (Strea7:ea'er rea'er = ;i!e.O2en6e<t(@"c=2erson.json"00
{
JObject o = (JObject0J6o>en.:ea';ro7(ne) Json6e<t:ea'er(rea'er001
(( 'o st3ff
/
Creating JSON
As well as pa!sing JSON !om existing JSON st!ings+ LINQ to JSON o"jects can "e c!eated !om sc!atch to c!eate new
JSON st!$ct$!es.
Manually Creating JSON
Setting &al$es and c!eating o"jects and a!!a%s one at a time gi&es %o$ total cont!ol "$t it is mo!e &e!"ose than othe!
options.
,!eating JSON
J9rra, arra, = ne) J9rra,(01
J&a!3e te<t = ne) J&a!3e("8an3a! te<t"01
J&a!3e 'ate = ne) J&a!3e(ne) #ate6i7e(?+++" *" ?@001
arra,.9''(te<t01
arra,.9''('ate01
string json = arra,.6oString(01
(( %
(( "8an3a! te<t""
(( "?+++A+*A?@6++++++"
(( .
Creating JSON with LINQ
-ecla!ati&el% c!eating JSON o"jects $sing LINQ is a ast wa% to c!eate JSON !om collections o &al$es.
,!eating JSON -ecla!ati&el%
List4Post5 2osts = BetPosts(01
JObject rss =
ne) JObject(
ne) JPro2ert,("c-anne!""
ne) JObject(
ne) JPro2ert,("tit!e"" "Ja7es Ne)tonACing"0"
ne) JPro2ert,("!in>"" "-tt2((ja7es.ne)ton>ing.co7"0"
ne) JPro2ert,("'escri2tion"" "Ja7es Ne)tonACing's b!og."0"
ne) JPro2ert,("ite7""
ne) J9rra,(
fro7 2 in 2osts
or'erb, 2.6it!e
se!ect ne) JObject(
ne) JPro2ert,("tit!e"" 2.6it!e0"
ne) JPro2ert,("'escri2tion"" 2.#escri2tion0"
ne) JPro2ert,("!in>"" 2.Lin>0"
ne) JPro2ert,("categor,""
ne) J9rra,(
fro7 c in 2.Categories
se!ect ne) J&a!3e(c0000000001
Conso!e.DriteLine(rss.6oString(001
(({
(( "c-anne!" {
(( "tit!e" "Ja7es Ne)tonACing""
(( "!in>" "-tt2((ja7es.ne)ton>ing.co7""
(( "'escri2tion" "Ja7es Ne)tonACing's b!og.""
(( "ite7" %
(( {
(( "tit!e" "Json.NE6 F.@ G Ne) !icense G No) on Co'eP!e<""
(( "'escri2tion" "9nno3cing t-e re!ease of Json.NE6 F.@" t-e 8I6 !icense an' being a$ai!ab!e on
Co'eP!e<""
(( "!in>" "-tt2((ja7es.ne)ton>ing.co7(2rojects(jsonAnet.as2<""
(( "categor," %
(( "Json.NE6""
(( "Co'eP!e<"
(( .
(( /"
(( {
(( "tit!e" "LINQ to JSON beta""
(( "'escri2tion" "9nno3cing LINQ to JSON""
(( "!in>" "-tt2((ja7es.ne)ton>ing.co7(2rojects(jsonAnet.as2<""
(( "categor," %
(( "Json.NE6""
(( "LINQ"
(( .
(( /
(( .
(( /
((/
Creating JSON from an object
.he last option is to c!eate a JSON o"ject !om a non/JSON t%pe $sing the *!omO"ject'( method. Inte!nall%
*!omO"ject will $se the JsonSe!iali0e! to se!iali0e the o"ject to LINQ to JSON o"jects instead o text.
.he example "elow is c!eating a JSON o"ject !om an anon%mo$s o"ject "$t an% .N1. t%pe can "e $sed with
*!omO"ject to c!eate JSON.
Creating JSON from an Objet
JObject o = JObject.;ro7Object(ne)
{
c-anne! = ne)
{
tit!e = "Ja7es Ne)tonACing""
!in> = "-tt2((ja7es.ne)ton>ing.co7""
'escri2tion = "Ja7es Ne)tonACing's b!og.""
ite7 =
fro7 2 in 2osts
or'erb, 2.6it!e
se!ect ne)
{
tit!e = 2.6it!e"
'escri2tion = 2.#escri2tion"
!in> = 2.Lin>"
categor, = 2.Categories
/
/
/01
Querying JSON with LINQ
LINQ to JSON p!o&ides a n$m"e! o methods o! getting data !om its o"jects. .he index methods on JO"ject/JA!!a%
let %o$ #$ickl% get data "% its p!ope!t% name on an o"ject o! index in a collection+ while ,hild!en'( lets %o$ get !anges
o data as I1n$me!a"le2J.oken3 to then #$e!% $sing LINQ.
!etting "alues by Pro#erty Name or Colletion Index
.he simplest wa% to get a &al$e !om LINQ to JSON is to $se the Item4O"ject5 index on JO"ject/JA!!a% and then cast
the !et$!ned J6al$e to the t%pe %o$ want.
7etting JSON 6al$es
st!ing json 8 9:;
<channel<: ;
<title<: <James Newton/=ing<+
<link<: <http://james.newtonking.com<+
<desc!iption<: <James Newton/=ing<s "log.<+
<item<: 4
;
<title<: <Json.N1. >.? @ New license @ Now on ,odePlex<+
<desc!iption<: <Anno$cing the !elease o Json.N1. >.?+ the AI. license and the so$!ce on ,odePlex<+
<link<: <http://james.newtonking.com/p!ojects/json/net.aspx<+
<catego!ies<: 4
<Json.N1.<+
<,odePlex<
5
B+
;
<title<: <LINQ to JSON "eta<+
<desc!iption<: <Anno$cing LINQ to JSON<+
<link<: <http://james.newtonking.com/p!ojects/json/net.aspx<+
<catego!ies<: 4
<Json.N1.<+
<LINQ<
5
B
5
B
B:C
JO"ject !ss 8 JO"ject.Pa!se'json(C
st!ing !ss.itle 8 'st!ing(!ss4:channel:54:title:5C
// James Newton/=ing
st!ing item.itle 8 'st!ing(!ss4:channel:54:item:54D54:title:5C
// Json.N1. >.? @ New license @ Now on ,odePlex
JA!!a% catego!ies 8 'JA!!a%(!ss4:channel:54:item:54D54:catego!ies:5C
// 4:Json.N1.:+ :,odePlex:5
IList2st!ing3 catego!ies.ext 8 catego!ies.Select'c 83 'st!ing(c(..oList'(C
// Json.N1.
// ,odePlex
Querying with LINQ
JO"ject/JA!!a% can also "e #$e!ied $sing LINQ. ,hild!en'( !et$!ns the child!en &al$es o a JO"ject/JA!!a% as an
I1n$me!a"le2J.oken3 that can then "e #$e!ied with the standa!d Ehe!e/O!de!F%/Select LINQ ope!ato!s.
Note
,hild!en'( !et$!ns all the child!en o a token. I it is a JO"ject it will !et$!n a collection o p!ope!ties to wo!k with and i it is a
JA!!a% %o$ will get a collection o the a!!a%<s &al$es.
Querying JSON
&a! post.itles 8
!om p in !ss4:channel:54:item:5
select 'st!ing(p4:title:5C
o!each '&a! item in post.itles(
;
,onsole.E!iteLine'item(C
B
//LINQ to JSON "eta
//Json.N1. >.? @ New license @ Now on ,odePlex
&a! catego!ies 8
!om c in !ss4:channel:54:item:5.,hild!en'(4:catego!%:5.6al$es2st!ing3'(
g!o$p c "% c into g
o!de!"% g.,o$nt'( descending
select new ; ,atego!% 8 g.=e%+ ,o$nt 8 g.,o$nt'( BC
o!each '&a! c in catego!ies(
;
,onsole.E!iteLine'c.,atego!% @ : / ,o$nt: : @ c.,o$nt(C
B
//Json.N1. / ,o$nt: G
//LINQ / ,o$nt: >
//,odePlex / ,o$nt: >
LINQ to JSON can also "e $sed to man$all% con&e!t JSON to a .N1. o"ject.
$eseriali%ing &sing LINQ Objets
p$"lic class Sho!tie
;
p$"lic st!ing O!iginal ; getC setC B
p$"lic st!ing Sho!tened ; getC setC B
p$"lic st!ing Sho!t ; getC setC B
p$"lic Sho!tie1xception 1!!o! ; getC setC B
B
p$"lic class Sho!tie1xception
;
p$"lic int ,ode ; getC setC B
p$"lic st!ing 1!!o!Aessage ; getC setC B
B
Aan$all% se!iali0ing and dese!iali0ing "etween .N1. o"jects is $se$l when %o$ a!e wo!king with JSON that doesn<t
closel% match %o$! .N1. o"jects.
$eseriali%ing &sing LINQ 'xam#le
st!ing json.ext 8 9:;
<sho!t<: ;
<o!iginal<: <http://www.oo.com/<+
<sho!t<: <k!eh#k<+
<e!!o!<: ;
<code<:D+
<msg<:<No action taken<
B
B:C
JO"ject json 8 JO"ject.Pa!se'json.ext(C
Sho!tie sho!tie 8 new Sho!tie
;
O!iginal 8 'st!ing(json4:sho!t:54:o!iginal:5+
Sho!t 8 'st!ing(json4:sho!t:54:sho!t:5+
1!!o! 8 new Sho!tie1xception
;
,ode 8 'int(json4:sho!t:54:e!!o!:54:code:5+
1!!o!Aessage 8 'st!ing(json4:sho!t:54:e!!o!:54:msg:5
B
BC
,onsole.E!iteLine'sho!tie.O!iginal(C
// http://www.oo.com/
,onsole.E!iteLine'sho!tie.1!!o!.1!!o!Aessage(C
// No action taken
Querying JSON with SelectToken
Select.oken'( p!o&ides a method to #$e!% LINQ to JSON $sing a single st!ing path to a desi!ed J.oken. Select.oken
makes d%namic #$e!ies eas% "eca$se the enti!e #$e!% is deined in a st!ing.
Selet(o)en
Select.oken is a method on J.oken and takes a st!ing path to a child token. Select.oken !et$!ns the child token o! a
n$ll !ee!ence i a token co$ldn<t "e o$nd at the path<s location.
.he path is made $p o p!ope!t% names and a!!a% indexes sepa!ated "% pe!iods. A!!a% indexes can $se eithe! s#$a!e o!
!o$nd "!ackets. Foth o the ollowing a!e &alid paths and a!e e#$i&alent to each othe!: Aan$act$!e!s4D5.Name and
Aan$act$!e!s'D(.Name.
Selet(o)en 'xam#le
JO"ject o 8 JO"ject.Pa!se'9:;
<Sto!es<: 4
<Lam"ton Q$a%<+
<Eillis St!eet<
5+
<Aan$act$!e!s<: 4
;
<Name<: <Acme ,o<+
<P!od$cts<: 4
;
<Name<: <An&il<+
<P!ice<: HD
B
5
B+
;
<Name<: <,ontoso<+
<P!od$cts<: 4
;
<Name<: <1l"ow 7!ease<+
<P!ice<: II.IH
B+
;
<Name<: <Jeadlight *l$id<+
<P!ice<: K
B
5
B
5
B:(C
st!ing name 8 'st!ing(o.Select.oken':Aan$act$!e!s4D5.Name:(C
// Acme ,o
decimal p!od$ctP!ice 8 'decimal(o.Select.oken':Aan$act$!e!s4D5.P!od$cts4D5.P!ice:(C
// HD
st!ing p!od$ctName 8 'st!ing(o.Select.oken':Aan$act$!e!s4>5.P!od$cts4D5.Name:(C
// 1l"ow 7!ease
Selet(o)en with LINQ
Select.oken can "e $sed in com"ination with standa!d LINQ methods.
Selet(o)en *ith LINQ 'xam#le
IList2st!ing3 sto!eNames 8 o.Select.oken':Sto!es:(.Select's 83 'st!ing(s(..oList'(C
// Lam"ton Q$a%
// Eillis St!eet
IList2st!ing3 i!stP!od$ctNames 8 o4:Aan$act$!e!s:5.Select'm 83
'st!ing(m.Select.oken':P!od$cts4>5.Name:((..oList'(C
// n$ll
// Jeadlight *l$id
decimal totalP!ice 8 o4:Aan$act$!e!s:5.S$m'm 83 'decimal(m.Select.oken':P!od$cts4D5.P!ice:((C
// >KI.IH
Performance Tip
O$t o the "ox Json.N1. is aste! than -ata,ont!actJsonSe!iali0e! and Ja&aSc!iptSe!iali0e!. Je!e a!e some tips to make
it go e&en aste!.
O#timi%e Memory &sage
.o keep an application consistantl% ast it is impo!tant to minimi0e the amo$nt o time the .N1. !amewo!k spends
pe!o!ming ga!"age collection. Allocating too man% o"jects+ o! allocating &e!% la!ge o"jects can slow down o! e&en halt
an application while ga!"age collection is in p!og!ess.
.o minimi0e memo!% $sage and the n$m"e! o o"jects allocated Json.N1. s$ppo!ts se!iali0ing and dese!iali0ing
di!ectl% to a st!eam. )eading o! w!iting JSON a piece at a time instead o ha&ing the enti!e JSON st!ing loaded into
memo!% is especiall% impo!tant when wo!king with JSON doc$ments g!eate! than LHk" in si0e to a&oid the JSON
st!ing ending $p in the la!ge o"ject heap.
$eseriali%e String
1HttpClient client = new HttpClient();
2
3// read the json into a string
4// string could potentially be ery large and cause !e!ory proble!s
"string json = client#$et%tring&sync('http(//www#test#co!/large#json')#)esult;
*
+,erson p = -sonConert#.eseriali/e0bject1,erson2(json);
$eseriali%e Stream
1HttpClient client = new HttpClient();
2
3using (%trea! s =
client#$et%trea!&sync('http(//www#test#co!/large#json')#)esult)
4using (%trea!)eader sr = new %trea!)eader(s))
"using (-son)eader reader = new -son3e4t)eader(sr))
*5
+ -son%eriali/er seriali/er = new -son%eriali/er();
6
7 // read the json 8ro! a strea!
19 // json si/e doesn:t !atter because only a s!all piece is read at a ti!e
8ro! the H33, re;uest
11 ,erson p = seriali/er#.eseriali/e1,erson2(reader);
12<
JsonCon"erters
Passing a Json,on&e!te! to Se!iali0eO"ject o! -ese!iali0eO"ject p!o&ides a simple wa% to completel% change how an
o"ject is se!iali0ed. .he!e is howe&e! a small o&e!headC the ,an,on&e!t method is called o! e&e!% &al$e to check
whethe! se!iali0ation sho$ld "e handled "% that Json,on&e!te!.
.he!e a!e a co$ple o wa%s to contin$e to $se Json,on&e!te!s witho$t an% o&e!head. .he simplest wa% is to speci% the
Json,on&e!te! $sing the Json,on&e!te!Att!i"$te. .his att!i"$te tells the se!iali0e! to alwa%s $se that con&e!te! when
se!iali0ing and dese!iali0ing the t%pe+ witho$t the check.
&se JsonCon"erter with JsonCon"erter+ttribute
1=-sonConerter(typeo8(,ersonConerter))>
2public class ,erson
35
4 public ,erson()
" 5
* ?i@es = new ?ist1string2();
+ <
6
7 public string Aa!e 5 get; set; <
19 public B?ist1string2 ?i@es 5 get; priate set; <
11<
I the class %o$ want to con&e!t isn<t %o$! own and %o$<!e $na"le to $se an att!i"$te a Json,on&e!te! can still "e $sed "%
c!eating %o$! own I,ont!act)esol&e!.
1public class ConerterContract)esoler ( .e8aultContract)esoler
25
3 public new static readonly ConerterContract)esoler Bnstance = new
ConerterContract)esoler();
4
" protected oerride -sonContract CreateContract(3ype object3ype)
* 5
+ -sonContract contract = base#CreateContract(object3ype);
6
7 // this will only be called once and then cached
19 i8 (object3ype == typeo8(.ate3i!e) CC object3ype ==
typeo8(.ate3i!e088set))
11 contract#Conerter = new -aa%cript.ate3i!eConerter();
12
13 return contract;
14 <
1"<
.he I,ont!act)esol&e! in the example a"o&e will set all -ate.imes to $se the Ja&aSc!ipt-ate,on&e!te!.
Manually Seriali%e
.he a"sol$te astest wa% to !ead and w!ite JSON is to $se Json.ext)eade!/Json.extE!ite! di!ectl% to man$all% se!iali0e
t%pes. Msing a !eade! o! w!ite! di!ectl% skips an% o the o&e!head !om a se!iali0e! s$ch as !election.
Manually seriali%e using Json(ext*riter
1public static string 3o-son(this ,erson p)
25
3 %tringDriter sw = new %tringDriter();
4 -son3e4tDriter writer = new -son3e4tDriter(sw);
"
* // 5
+ writer#Drite%tart0bject();
6
7 // 'na!e' ( '-erry'
19 writer#Drite,ropertyAa!e('na!e');
11 writer#DriteEalue(p#Aa!e);
12
13 // 'li@es'( ='Co!edy'F '%uper!an'>
14 writer#Drite,ropertyAa!e('li@es');
1" writer#Drite%tart&rray();
1* 8oreach (string li@e in p#?i@es)
1+ 5
16 writer#DriteEalue(li@e);
17 <
29 writer#DriteGnd&rray();
21
22 // <
23 writer#DriteGnd0bject();
24
2" return sw#3o%tring();
2*<
I pe!o!mance is impo!tant and %o$ don<t mind mo!e code to get it then this is %o$! "est choice. )ead mo!e a"o$t $sing
Json)eade!/JsonE!ite! he!e: Fasic )eading and E!iting JSON 'link non atti&o(
6alidating JSON with JSON Schema
Json.N1. s$ppo!ts the JSON Schema standa!d &ia the JsonSchema and
Json6alidating)eade! classes. It sits $nde! the Newtonsot.Json.Schema namespace.
JSON Schema is $sed to &alidate the st!$ct$!e and data t%pes o a piece o JSON+ simila!
to NAL Schema o! NAL. )ead mo!e a"o$t JSON Schema at json/schema.o!g
,alidating with JSON Shema
.he simplest wa% to check i JSON is &alid is to load the JSON into a JO"ject o! JA!!a%
and then $se the Is6alid'J.oken+ JsonSchema( method with the JSON Schema
6alidate JSON with Is6alid
st!ing schemaJson 8 9:;
<desc!iption<: <A pe!son<+
<t%pe<: <o"ject<+
<p!ope!ties<:
;
<name<: ;<t%pe<:<st!ing<B+
<ho""ies<: ;
<t%pe<: <a!!a%<+
<items<: ;<t%pe<:<st!ing<B
B
B
B:C
JsonSchema schema 8 JsonSchema.Pa!se'schemaJson(C
JO"ject pe!son 8 JO"ject.Pa!se'9:;
<name<: <James<+
<ho""ies<: 4<.N1.<+ <Flogging<+ <)eading<+ <N"ox<+ <LOL,A.S<5
B:(C
"ool &alid 8 pe!son.Is6alid'schema(C
// t!$e
.o get &alidation e!!o! messages $se the Is6alid'J.oken+ JsonSchema+ IList2St!ing3( o!
6alidate'J.oken+ JsonSchema+ 6alidation1&entJandle!( o&e!loads.
,alidate JSON with Is,alid
JsonSchema schema 8 JsonSchema.Pa!se'schemaJson(C
JO"ject pe!son 8 JO"ject.Pa!se'9:;
<name<: n$ll+
<ho""ies<: 4<In&alid content<+ D.>G?KHOPLI5
B:(C
IList2st!ing3 messagesC
"ool &alid 8 pe!son.Is6alid'schema+ o$t messages(C
// alse
// In&alid t%pe. 1xpected St!ing "$t got N$ll. Line G+ position G>.
// In&alid t%pe. 1xpected St!ing "$t got *loat. Line ?+ position H>.
Inte!nall% Is6alid $ses Json6alidating)eade! to pe!o!m the JSON Schema &alidation. .o
skip the o&e!head o loading JSON into a JO"ject/JA!!a%+ &alidating the JSON and then
dese!iali0ing the JSON into a class+ Json6alidating)eade! can "e $sed with JsonSe!iali0e!
to &alidate JSON while the o"ject is "eing dese!iali0ed.
,alidate JSON with Json,alidating-eader
st!ing json 8 9:;
<name<: <James<+
<ho""ies<: 4<.N1.<+ <Flogging<+ <)eading<+ <N"ox<+ <LOL,A.S<5
B:C
Json.ext)eade! !eade! 8 new Json.ext)eade!'new St!ing)eade!'json((C
Json6alidating)eade! &alidating)eade! 8 new Json6alidating)eade!'!eade!(C
&alidating)eade!.Schema 8 JsonSchema.Pa!se'schemaJson(C
IList2st!ing3 messages 8 new List2st!ing3'(C
&alidating)eade!.6alidation1&entJandle! @8 'o+ a( 83 messages.Add'a.Aessage(C
JsonSe!iali0e! se!iali0e! 8 new JsonSe!iali0e!'(C
Pe!son p 8 se!iali0e!.-ese!iali0e2Pe!son3'&alidating)eade!(C
Creating JSON Shemas
.he simplest wa% to get a JsonSchema o"ject is to load it !om a st!ing o! a ile.
Creating JSON Shemas from strings or files
// load !om a st!ing
JsonSchema schema> 8 JsonSchema.Pa!se'9:;<t%pe<:<o"ject<B:(C
// load !om a ile
$sing '.ext)eade! !eade! 8 *ile.Open.ext'9:c:QschemaQPe!son.json:((
;
JsonSchema schemaG 8 JsonSchema.)ead'new Json.ext)eade!'!eade!((C
// do st$
B
It is also possi"le to c!eate JsonSchema o"jects in code.
Create new JSON Shemas in ode
JsonSchema schema 8 new JsonSchema'(C
schema..%pe 8 JsonSchema.%pe.O"jectC
schema.P!ope!ties 8 new -ictiona!%2st!ing+ JsonSchema3
;
;:name:+ new JsonSchema ;.%pe 8 JsonSchema.%pe.St!ingBB+
;
:ho""ies:+ new JsonSchema
;
.%pe 8 JsonSchema.%pe.A!!a%+
Items 8 new List2JsonSchema3 ; new JsonSchema ;.%pe 8 JsonSchema.%pe.St!ingB B
B
B+
BC
JO"ject pe!son 8 JO"ject.Pa!se'9:;
<name<: <James<+
<ho""ies<: 4<.N1.<+ <Flogging<+ <)eading<+ <N"ox<+ <LOL,A.S<5
B:(C
"ool &alid 8 pe!son.Is6alid'schema(C
// t!$e
!aic "ea#ing an# $riting JSON
.o man$all% !ead and w!ite JSON Json.N1. p!o&ides the Json)eade! and JsonE!ite! classes.
Json(ext-eader and Json(ext*riter
Note
Json)eade! and JsonE!ite! a!e low le&el classes and $sed inte!nall% "% Json.N1.. .o #$ickl% wo!k with JSON eithe! the
se!iali0e! / Se!iali0ing and -ese!iali0ing JSON o! $sing LINQ to JSON is !ecommended.
Json.ext)eade! and Json.extE!ite! a!e $sed to !ead and w!ite JSON text. .he Json.extE!ite! has a n$m"e! o settings
on it to cont!ol how JSON is o!matted when it is w!itten. .hese options incl$de o!matting+ indention cha!acte!+ indent
co$nt and #$ote cha!acte!.
*riting JSON with Json(ext*riter
St!ingF$ilde! s" 8 new St!ingF$ilde!'(C
St!ingE!ite! sw 8 new St!ingE!ite!'s"(C
$sing 'JsonE!ite! w!ite! 8 new Json.extE!ite!'sw((
;
w!ite!.*o!matting 8 *o!matting.IndentedC
w!ite!.E!iteSta!tO"ject'(C
w!ite!.E!iteP!ope!t%Name':,PM:(C
w!ite!.E!ite6al$e':Intel:(C
w!ite!.E!iteP!ope!t%Name':PSM:(C
w!ite!.E!ite6al$e':HDDE:(C
w!ite!.E!iteP!ope!t%Name':-!i&es:(C
w!ite!.E!iteSta!tA!!a%'(C
w!ite!.E!ite6al$e':-6- !ead/w!ite!:(C
w!ite!.E!ite,omment':'"!oken(:(C
w!ite!.E!ite6al$e':HDD giga"%te ha!d d!i&e:(C
w!ite!.E!ite6al$e':GDD giga"%pe ha!d d!i&e:(C
w!ite!.E!ite1nd'(C
w!ite!.E!ite1ndO"ject'(C
B
// ;
// :,PM:: :Intel:+
// :PSM:: :HDDE:+
// :-!i&es:: 4
// :-6- !ead/w!ite!:
// /R'"!oken(R/+
// :HDD giga"%te ha!d d!i&e:+
// :GDD giga"%pe ha!d d!i&e:
// 5
// B
Json.ext)eade! has settings on it o! !eading die!ent date o!mats and time 0ones+ and the c$lt$!e $sed when !eading
text &al$es.
-eading JSON with Json(ext-eader
st!ing json 8 9:;
<,PM<: <Intel<+
<PSM<: <HDDE<+
<-!i&es<: 4
<-6- !ead/w!ite!<
/R'"!oken(R/+
<HDD giga"%te ha!d d!i&e<+
<GDD giga"%pe ha!d d!i&e<
5
B:C
Json.ext)eade! !eade! 8 new Json.ext)eade!'new St!ing)eade!'json((C
while '!eade!.)ead'((
;
i '!eade!.6al$e S8 n$ll(
,onsole.E!iteLine':.oken: ;DB+ 6al$e: ;>B:+ !eade!..oken.%pe+ !eade!.6al$e(C
else
,onsole.E!iteLine':.oken: ;DB:+ !eade!..oken.%pe(C
B
// .oken: Sta!tO"ject
// .oken: P!ope!t%Name+ 6al$e: ,PM
// .oken: St!ing+ 6al$e: Intel
// .oken: P!ope!t%Name+ 6al$e: PSM
// .oken: St!ing+ 6al$e: HDDE
// .oken: P!ope!t%Name+ 6al$e: -!i&es
// .oken: Sta!tA!!a%
// .oken: St!ing+ 6al$e: -6- !ead/w!ite!
// .oken: ,omment+ 6al$e: '"!oken(
// .oken: St!ing+ 6al$e: HDD giga"%te ha!d d!i&e
// .oken: St!ing+ 6al$e: GDD giga"%pe ha!d d!i&e
// .oken: 1ndA!!a%
// .oken: 1ndO"ject
J(o)en-eader and J(o)en*riter
J.oken)eade! and J.okenE!ite! !ead and w!ite LINQ to JSON o"jects. .he% a!e located in the Newtonsot.Json.Lin#
namespace. .hese o"jects allow %o$ to $se LINQ to JSON o"jects with o"jects that !ead and w!ite JSON s$ch as the
JsonSe!iali0e!. *o! example %o$ can dese!iali0e !om a LINQ to JSON o"ject into a !eg$la! .N1. o"ject and &ice &e!sa.
$eseriali%ing with J(o)en-eader
JO"ject o 8 new JO"ject'
new JP!ope!t%':Name:+ :John Smith:(+
new JP!ope!t%':Fi!th-ate:+ new -ate.ime'>IL?+ ?+ GD((
(C
JsonSe!iali0e! se!iali0e! 8 new JsonSe!iali0e!'(C
Pe!son p 8 'Pe!son(se!iali0e!.-ese!iali0e'new J.oken)eade!'o(+ t%peo'Pe!son((C
,onsole.E!iteLine'p.Name(C
// John Smith
Con%erting between JSON an# &'L
Json.N1. s$ppo!ts con&e!ting JSON to NAL and &ice &e!sa $sing the NmlNode,on&e!te!.
1lements+ att!i"$tes+ text+ comments+ cha!acte! data+ p!ocessing inst!$ctions+ namespaces and the NAL decla!ation a!e
all p!ese!&ed when con&e!ting "etween the two. .he onl% ca&eat is that it is possi"le to lose the o!de! o die!entl%
named nodes at the same le&el when the% a!e g!o$ped togethe! into an a!!a%.
Con"ersion -ules
1lements !emain $nchanged.
Att!i"$tes a!e p!eixed with an 9 and sho$ld "e at the sta!t o the o"ject.
Single child text nodes a!e a &al$e di!ectl% against an element+ othe!wise the% a!e accessed &ia Ttext.
.he NAL decla!ation and p!ocessing inst!$ctions a!e p!eixed with U.
,ha!ate! data+ comments+ whitespace and signiicate whitespace nodes a!e accessed &ia Tcdata/section+
Tcomment+ Twhitespace and Tsigniicate/whitespace !especti&el%.
A$ltiple nodes with the same name at the same le&el a!e g!o$ped togethe! into an a!!a%.
1mpt% elements a!e n$ll.
I the NAL c!eated !om JSON doesn<t match what %o$ want then %o$ will need to con&e!t it man$all%. .he "est
app!oach to do this is to load %o$! JSON into a LINQ to JSON o"ject like JO"ject o! JA!!a% and then $se LINQ to
c!eate an N-oc$ment. .he opposite p!ocess+ $sing LINQ with an N-oc$ment to c!eate a JO"ject o! JA!!a%+ also
wo!ks. *ind o$t mo!e a"o$t $sing LINQ to JSON with LINQ he!e.
Note
.he &e!sion o Json.N1. "eing $sed in %o$! application will change what NAL con&e!sion methods a!e a&aila"le.
Se!iali0eNmlNode/-ese!iali0eNmlNode a!e a&aila"le when the !amewo!k s$ppo!ts Nml-oc$ment+
Se!iali0eNNode/-ese!iali0eNNode a!e a&aila"le when the !amewo!k s$ppo!ts N-oc$ment.
Seriali%e.mlNode
.he Json,on&e!t has two helpe! methods o! con&e!ting "etween JSON and NAL. .he i!st is Se!iali0eNmlNode'(.
.his method takes an NmlNode and se!iali0es it to JSON text.
Con"erting .ML to JSON with Seriali%e.mlNode
st!ing xml 8 9:2Uxml &e!sion8<>.D< standalone8<no<U3
2!oot3
2pe!son id8<><3
2name3Alan2/name3
2$!l3http://www.google.com2/$!l3
2/pe!son3
2pe!son id8<G<3
2name3Lo$is2/name3
2$!l3http://www.%ahoo.com2/$!l3
2/pe!son3
2/!oot3:C
Nml-oc$ment doc 8 new Nml-oc$ment'(C
doc.LoadNml'xml(C
st!ing json.ext 8 Json,on&e!t.Se!iali0eNmlNode'doc(C
//;
// :Uxml:: ;
// :9&e!sion:: :>.D:+
// :9standalone:: :no:
// B+
// :!oot:: ;
// :pe!son:: 4
// ;
// :9id:: :>:+
// :name:: :Alan:+
// :$!l:: :http://www.google.com:
// B+
// ;
// :9id:: :G:+
// :name:: :Lo$is:+
// :$!l:: :http://www.%ahoo.com:
// B
// 5
// B
//B
Feca$se m$ltiple nodes with a the same name at the same le&el a!e g!o$ped togethe! into an a!!a% the con&e!nsion
p!ocess can p!od$ce die!ent JSON depending on the n$m"e! o nodes. *o! example i some NAL o! a $se! has a
single 2)ole3 node then that !ole will "e text against a JSON :)ole: p!ope!t%+ "$t i the $se! has m$ltiple 2)ole3
nodes then the !ole &al$es will "e placed in a JSON a!!a%.
.o ix this sit$ation a c$stom NAL att!i"$te can "e added to o!ce a JSON a!!a% to "e c!eated.
+ttribute to /ore a JSON +rray
st!ing xml 8 9:2pe!son id8<><3
2name3Alan2/name3
2$!l3http://www.google.com2/$!l3
2!ole3Admin>2/!ole3
2/pe!son3:C
Nml-oc$ment doc 8 new Nml-oc$ment'(C
doc.LoadNml'xml(C
st!ing json 8 Json,on&e!t.Se!iali0eNmlNode'doc(C
//;
// :pe!son:: ;
// :9id:: :>:+
// :name:: :Alan:+
// :$!l:: :http://www.google.com:+
// :!ole:: :Admin>:
// B
//B
xml 8 9:2pe!son xmlns:json8<http://james.newtonking.com/p!ojects/json< id8<><3
2name3Alan2/name3
2$!l3http://www.google.com2/$!l3
2!ole json:A!!a%8<t!$e<3Admin2/!ole3
2/pe!son3:C
doc 8 new Nml-oc$ment'(C
doc.LoadNml'xml(C
json 8 Json,on&e!t.Se!iali0eNmlNode'doc(C
//;
// :pe!son:: ;
// :9id:: :>:+
// :name:: :Alan:+
// :$!l:: :http://www.google.com:+
// :!ole:: 4
// :Admin:
// 5
// B
//B
$eseriali%e.mlNode
.he second helpe! method on Json,on&e!t is -ese!iali0eNmlNode'(. .his method takes JSON text and dese!iali0es it
into a NmlNode.
Feca$se &alid NAL m$st ha&e one !oot element the JSON passed to -ese!iali0eNmlNode sho$ld ha&e one p!ope!t% in
the !oot JSON o"ject. I the !oot JSON o"ject has m$ltiple p!ope!ties then the o&e!load that also takes an element name
sho$ld "e $sed. A !oot element with that name will "e inse!ted into the dese!iali0ed NmlNode.
Con"erting JSON to .ML with $eseriali%e.mlNode
st!ing json 8 9:;
<Uxml<: ;
<9&e!sion<: <>.D<+
<9standalone<: <no<
B+
<!oot<: ;
<pe!son<: 4
;
<9id<: <><+
<name<: <Alan<+
<$!l<: <http://www.google.com<
B+
;
<9id<: <G<+
<name<: <Lo$is<+
<$!l<: <http://www.%ahoo.com<
B
5
B
B:C
Nml-oc$ment doc 8 'Nml-oc$ment(Json,on&e!t.-ese!iali0eNmlNode'json(C
// 2Uxml &e!sion8:>.D: standalone8:no:U3
// 2!oot3
// 2pe!son id8:>:3
// 2name3Alan2/name3
// 2$!l3http://www.google.com2/$!l3
// 2/pe!son3
// 2pe!son id8:G:3
// 2name3Lo$is2/name3
// 2$!l3http://www.%ahoo.com2/$!l3
// 2/pe!son3
// 2/!oot3
Jon(N)T % (N)T Seriali*er
*eat$!e ,ompa!ison
Json.N1. &s Eindows.-ata.Json
Eindows L int!od$ces a new wa% to wo!k with JSON &ia the Eindows.-ata.Json namespace. Simila! to LINQ to
JSON in Json.N1. it deines classes that can "e $sed to pa!se &al$es+ st!ings+ o"jects+ and a!!a%s !om JSON text o!
se!iali0e &al$e t%pes into JSON text.
Felow is a compa!ison o Json.N1.<s LINQ to JSON to Eindow L<s Eindows.-ata.Json.
'xlusi"e Json0N'( /eatures
)$ns on .N1. G+ .N1. ?+ .N1. K+ Sil&e!light and Eindows Phone P
-%namic p!og!amming
E!ite indented JSON
,$stomi0e !eading and w!iting JSON with Json,on&e!te!s
)ead and w!ite ISOLOD> dates
Fette! LINQ s$ppo!t
Creating JSON
.he "ig die!ence "etween the two li"!a!ies when c!eating JSON is Eindows.-ata.Json !e#$i!es st!ing/intege!/do$"le
&al$es to "e explicitl% con&e!ted to Json6al$e o"jects.
Note that the!e is a wei!d limitation to c!eating JSON with Eindows.-ata.Json: it doesn<t allow %o$ to set p!ope!ties to
n$ll o! p$t n$ll &al$es in an a!!a%.
Creating JSON with Json0N'( and *indows0$ata0Json
1// Dindows#.ata#-son
2// HHHHHHHHHHHHHHHHH
3-son0bject json0bject = new -son0bject
4 5
" 5'C,I'F -sonEalue#Create%tringEalue('Bntel')<F
* 5
+ '.ries'F new -son&rray
6 5
7 -sonEalue#Create%tringEalue('.E. read/writer')F
19 -sonEalue#Create%tringEalue('"99 gigabyte hard drie')
11 <
12 <
13 <;
14string json1 = json0bject#%tringi8y();
1"
1*// ?BAJ to -%0A
1+// HHHHHHHHHHHH
16-0bject j0bject = new -0bject
17 5
29 5'C,I'F 'Bntel'<F
21 5
22 '.ries'F new -&rray
23 5
24 '.E. read/writer'F
2" '"99 gigabyte hard drie'
2* <
2+ <
26 <;
27string json2 = j0bject#3o%tring();
Querying JSON
Eindows.-ata.Json !e#$i!es a &al$e to "e cast to its exact t%pe with the 7etO"ject/7etA!!a% methods "eo!e it can "e
$sed+ making Eindows.-ata.Json<s code &e!"ose compa!ed to LINQ to JSON.
Querying JSON with Json0N'( and *indows0$ata0Json
1string json = K'5
2 :channel:( 5
3 :title:( :-a!es AewtonHLing:F
4 :lin@:( :http(//ja!es#newton@ing#co!:F
" :description:( :-a!es AewtonHLing:s blog#:F
* :ite!:( =
+ 5
6 :title:( :-son#AG3 1#3 M Aew license M Aow on Code,le4:F
7 :description:( :&nnoucing the release o8 -son#AG3 1#3F the NB3 license
and the source on Code,le4:F
19 :lin@:( :http(//ja!es#newton@ing#co!/projects/jsonHnet#asp4:F
11 :category:( =
12 :-son#AG3:F
13 :Code,le4:
14 >
1" <
1* >
1+ <
16<';
17
29// Dindows#.ata#-son
21// HHHHHHHHHHHHHHHHH
22-son0bject json0bject = -son0bject#,arse(json);
23string ite!3itle1 = json0bject='channel'>#$et0bject()='ite!'>#$et&rray()
=9>#$et0bject()='title'>#$et%tring();
24
2"// ?BAJ to -%0A
2*// HHHHHHHHHHHH
2+-0bject j0bject = -0bject#,arse(json);
26string ite!3itle2 = (string)j0bject='channel'>='ite!'>=9>='title'>;
///// s$ sito /////////
O&e! >DD code samples co&e!ing Json.N1.<s most commonl% $sed $nctionalit%.
Sam#les
Seriali%ing JSON / Se!iali0ing and dese!iali0ing JSON+ se!iali0e! settings and se!iali0ation att!i"$tes
LINQ to JSON / Pa!sing+ #$e!%ing+ modi%ing and w!iting JSON
JSON Shema / Loading schemas and &alidating JSON
Con"erting .ML / ,on&e!ting JSON to NAL and NAL to JSON
1SON / Se!iali0ing and dese!iali0ing FSON
-eading and *riting JSON / )eading JSON with Json.ext)eade!+ w!iting JSON with Json.extE!ite!
API )ee!ence
Names#aes
Names#ae $esri#tion
Newtonsot.Json
.he Newtonsoft0Json namespace p!o&ides classes that a!e $sed to implement the co!e se!&ices o the
!amewo!k.
Newtonsot.Json.Fson .he Newtonsoft0Json0Lin2 namespace p!o&ides classes that a!e $sed to implement FSON.
Newtonsot.Json.,on&e!te!
s
.he Newtonsoft0Json0Con"erters namespace p!o&ides classes that inhe!it !om Json,on&e!te!.
Newtonsot.Json.Lin# .he Newtonsoft0Json0Lin2 namespace p!o&ides classes that a!e $sed to implement LINQ to JSON.
Newtonsot.Json.Schema .he Newtonsoft0Json0Shema namespace p!o&ides classes that a!e $sed to implement JSON schema.
Newtonsot.Json.Se!iali0ati
on
.he Newtonsoft0Json0Lin2 namespace p!o&ides classes that a!e $sed when se!iali0ing and
dese!iali0ing JSON.
http://james.newtonking.com/json
http://james.newtonking.com/json/help/index.html

S-ar putea să vă placă și