Transcript
  • Json.NET-QuickStarts&APIDocumentationIntroduction

    Json.NETmakesworkingwithJSONformatteddatain.NETsimple.QuicklyreadandwriteJSONusingLINQtoJSONorserializeyour.NETobjectswithasinglemethodcallusingtheJsonSerializer.

    Features

    FlexibleJSONserializertoconvert.NETobjectstoJSONandbackagainLINQtoJSONforreadingandwritingJSONWritesindented,easytoreadJSONConvertJSONtoandfromXMLSupportsSilverlightandtheCompactFramework

    TheJSONserializerisagoodchoicewhentheJSONyouarereadingorwritingmapscloselytoa.NETclass.TheserializerautomaticallyreadsandwritesJSONfortheclass.

    ForsituationswhereyouareonlyinterestedingettingvaluesfromJSON,don'thaveaclasstoserializeordeserializeto,ortheJSONisradicallydifferentfromyourclassandyouneedtomanuallyreadandwritefromyourobjectsthenLINQtoJSONiswhatyoushoulduse.LINQtoJSONallowsyoutoeasilyread,createandmodifyJSONin.NET.

    History

    Json.NETgrewoutofprojectsIwasworkingoninlate2005involvingJavaScript,AJAXand.NET.AtthetimetherewerenolibrariesforworkingwithJavaScriptin.NETsoIbegantogrowmyown.

    StartingoutasacoupleofstaticmethodsforescapingJavaScriptstrings,Json.NETevolvedasfeatureswereadded.ToaddsupportforreadingJSONamajorrefactorwasrequiredandJson.NETwillsplitintothethreemajorclassesitstillusestoday,JsonReader,JsonWriterandJsonSerializer.

  • Json.NETwasfirstreleasedinJune2006.SincethenJson.NEThasbeendownloadedthousandsoftimesbydevelopersandisusedinanumberofmajorprojectsopensourceprojectsincludingMonoRail,CastleProject'sMVCwebframework,andMono,anopensourceimplementationofthe.NETframework.

    ~JamesNewton-King

    Donate

    Json.NETisafreeopensourceprojectthatIhavedevelopedinmypersonaltime.

    IreallyappreciateyourfeedbackandsupportforJson.NETanditsfuturedevelopment.

    http://www.castleproject.org/monorail/index.htmlhttp://www.mono-project.com/https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=james%40newtonking%2ecom&item_name=Supporting%20Json%2eNET&no_shipping=0&no_note=1&tax=0&currency_code=USD&lc=US&bn=PP%2dDonationsBF&charset=UTF%2d8

  • Json.NET-QuickStarts&APIDocumentationSerializinganddeserializingJSON

    ThequickestmethodofconvertingbetweenJSONtextanda.NETobjectisusingtheJsonSerializer.TheJsonSerializerconverts.NETobjectsintotheirJSONequivalentandbackagain.

    ForsimplescenarioswhereyouwanttoconverttoandfromaJSONstringtheSerializeObjectandDeserializeObjectmethodsonJsonConvertprovideaneasytousewrapperoverJsonSerializer.

    Productproduct=newProduct();product.Name="Apple";product.Expiry=newDateTime(2008,12,28);product.Price=3.99M;product.Sizes=newstring[]{"Small","Medium"stringoutput=JsonConvert.SerializeObject(product);//{//"Name":"Apple",//"Expiry":"\/Date(1230375600000+1300)\/",//"Price":3.99,//"Sizes":[//"Small",//"Medium",//"Large"//]//}ProductdeserializedProduct=JsonConvert.DeserializeObject

  • JsonSerializer

    FormorecontroloverhowanobjectisserializedtheJsonSerializercanbeuseddirectly.TheJsonSerializerisabletoreadandwriteJSONtextdirectlytoastreamviaJsonTextReaderandJsonTextWriter.OtherkindsofJsonWriterscanalsobeusedsuchasJTokenReader/JTokenWritertoconvertyourobjecttoandfromLINQtoJSONobjectsorBsonReader/BsonWritertoconverttoandfromBSON.

    Productproduct=newProduct();product.Expiry=newDateTime(2008,12,28);JsonSerializerserializer=newJsonSerializerserializer.Converters.Add(newJavaScriptDateTimeConverterserializer.NullValueHandling=NullValueHandlingusing(StreamWritersw=newStreamWriter(@"c:\json.txt"using(JsonWriterwriter=newJsonTextWriter(sw)){serializer.Serialize(writer,product);//{"Expiry":newDate(1230375600000),"Price":0}}

    JsonSerializerhasanumberofpropertiesonittocustomizehowitserializesJSON.ThesecanalsobeusedwiththemethodsonJsonConvertviatheJsonSerializerSettingsoverloads.

    ReferenceLoopHandling

    Controlshowcircularreferencingobjectsareserialized.Error,ignoreorserialize.

    MissingMemberHandling

  • Controlshowmissingmembers(e.g.JSONcontainsapropertythatisn'tamemberontheobject)arehandledduringdeserialization.Ignoreorerror.

    NullValueHandling

    Controlshownullvaluesarehandledduringserializationanddeserialization.Includeorignore.

    DefaultValueHandling

    ControlswhetheravaluewillbewrittentoJSONornotifitmatchesthevaluespecifiedinthemember'sDefaultValueAttribute.Includeorignore.

    ObjectCreationHandling

    Controlshowobjectsarecreatedduringdeserialization.Auto,reuse,replace.

    TypeNameHandling

    Controlswhether.NETtypenamesareincludedinserializedJSONandreadduringdeserializationwhencreatingobjects.None,Objects,ArraysorAll.

    ConstructorHandling

    Controlshowconstructorsareusedwheninitializingobjectsduringdeserialization.DefaultorAllowNonPublicDefaultConstructor.

    Converters

    AcollectionofJsonConvertersthatwillbeusedduringserializationanddeserialization.

    JsonConverters

    JsonConvertersallowsJSONtobemanuallywrittenduring

  • serializationandreadduringdeserialization.ThisisusefulforparticularlycomplexJSONstructuresorforwhenyouwanttochangehowatypeisserialized.

    TocreateyourowncustomconverterinheritfromtheJsonConverterclass.Json.NETalsocomeswithanumberofJsonConverters:

    DateTimeJSONConverters

    Json.NETcomeswithanumberofJsonConvertersforserializinganddeserializingDateTimes.ReadmoreaboutdatesandJson.NEThere.

    XmlNodeConverter

    ConvertsanXmlNodetoandfromJSON.NotethattoconvertaJSONobjectitmusthaveonlyasinglepropertyoryoumustdefinearootnodenametobeinsertedwhenusingthisconverter.ThisisrequiredbecausepropertiesareconvertedintonodesandwellformedXMLcanonlyhaveonerootnode.XmlNodeConverterhasanoptiontoinsertarootnodeforyou.

    BinaryConverter

    ConvertsbinarydataliketheSqlBinaryobjecttoJSON.ThebinarydataiswrittenasastringinJSONandisencodedinBase64.

    CustomCreationConverter

    AnabstractJsonConverterforcustomizinghowanobjectiscreateduringdeserialization.InheritfromthisclassandimplementtheCreatemethodwithyourowncodetocreateandreturnanobject.TheobjectwillthenbepopulatedwithJSONvaluesbytheserializer.

    Apossibleexampleofusingthisconverterwouldbetocallouttoadependencyinjectionframeworktoresolvewhatobjectshouldbecreated.

  • Json.NET-QuickStarts&APIDocumentationCustomizingJSONserializationwithattributes

    AttributescanbeusedtocontrolhowJson.NETserializesanddeserializes.NETobjects.

    JsonObjectAttribute-PlacedonclassestocontrolhowitshouldbeserializedasaJSONobject.JsonArrayAttribute-PlacedoncollectionstocontrolhowitshouldbeserializedasaJSONarray.JsonPropertyAttribute-PlacedonfieldsandpropertiestocontrolhowitshouldbeserializedasapropertyinaJSONobject.JsonConverterAttribute-PlacedoneitherclassesorfieldsandpropertiestospecifywhichJsonConvertershouldbeusedduringserialization.

    Aswellasusingthebuilt-inJson.NETattributes,Json.NETalsolooksfortheDataContractandDataMemberattributeswhendetermininghowJSONistobeserializedanddeserialized.IfbotharepresenttheJson.NETserializationattributestakeprecedence.

    [JsonObject(MemberSerialization.OptIn)]publicclassPerson{//"JohnSmith"[JsonProperty]publicstringName{get;set;}//"2000-12-15T22:11:03"[JsonProperty][JsonConverter(typeof(IsoDateTimeConverter))]publicDateTimeBirthDate{get;set;}//newDate(976918263055)[JsonProperty]

    http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspxhttp://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx

  • [JsonConverter(typeof(JavaScriptDateTimeConverterpublicDateTimeLastModified{get;set;}//notserializedpublicstringDepartment{get;set;}}

    JsonObjectAttribute

    TheMemberSerializationflagonthisattributespecifieswhethermemberserializationisopt-in(amembermusthavetheJsonPropertyorDataMemberattributetobeserialized)oropt-out(everythingisserializedbydefaultbutcanbeignoredwiththeJsonIgnoreAttribute,Json.NET'sdefaultbehavor).

    Json.NETserializes.NETclassesthatimplementIEnumerableasanJSONarraypopulatedwiththeIEnumerablevalues.PlacingtheJsonPropertyAttributeoverridesthisbehavorandforcestheserializertoserializetheclass'sfieldsandproperties.

    JsonPropertyAttribute

    JsonPropertyAttributehasanumberofuses:

    BydefaulttheJSONpropertywillhavethesamenameasthe.NETproperty.Thisattributeallowsthenametobecustomized.Indicatesthatapropertyshouldbeserializedwhenmemberserializationissettoopt-in.Includesnon-publicpropertiesinserializationanddeserialization.

    JsonIgnoreAttribute

    Excludesafieldorpropertyfromserialization.

    JsonConverterAttribute

    TheJsonConverterAttributespecifieswhichJsonSerializerisusedto

  • convertanobject.

    Theattributecanbeplacedonaclassoramember.WhenplacedonaclasstheJsonConverterspecifiedbytheattributewillbethedefaultwayofserializingthatclass.WhentheattributeisonafieldorpropertythenthespecifiedJsonConverterwillalwaysbeusedtoserializethatvalue.

    ThepriorityofwhichJsonConverterisusedismemberattributethenclassattributeandfinallyanyconverterspassedtotheJsonSerializer.

    publicclassMemberConverterClass{publicDateTimeDefaultConverter{get;set;}[JsonConverter(typeof(IsoDateTimeConverter))]publicDateTimeMemberConverter{get;set;}}

    ThisexampleshowstheJsonConverterAttributebeingappliedtoaproperty.

    DateTimedate=Convert.ToDateTime("1970-01-01T00:00:00Z"MemberConverterClassc=newMemberConverterClass{DefaultConverter=date,MemberConverter=date};stringjson=JsonConvert.SerializeObject(c,FormattingConsole.WriteLine(json);//{

  • //"DefaultConverter":"\/Date(0)\/",//"MemberConverter":"1970-01-01T00:00:00Z"//}

  • Json.NET-QuickStarts&APIDocumentationSerializingDatesinJSON

    DateTimesinJSONarehard.

    TheproblemcomesfromtheJSONspecitself,thereisnoliteralsyntaxfordatesinJSON.Thespechasobjects,arrays,strings,integersandfloats,butitdefinesnostandardforwhatadatelookslike.

    ThedefaultformatusedbyJson.NETfordatesisthesameoneusedbyMicrosoft:"\/Date(1198908717056)\/".Youcanreadmoreaboutithere.

    DateTimeJsonConverters

    WithnostandardfordatesinJSON,thenumberofpossibledifferentformatswheninteropingwithothersystemsisendless.FortunatelyJson.NEThasasolutiontodealwithreadingandwritingcustomdates:JsonConverters.AJsonConverterisusedtooverridehowatypeisserialized.

    publicclassLogEntry{publicstringDetails{get;set;}publicDateTimeLogDate{get;set;}}[Test]publicvoidWriteJsonDates(){LogEntryentry=newLogEntry{LogDate=newDateTime(2009,2,15,0,0,0,Details="Applicationstarted."};

    http://www.ietf.org/rfc/rfc4627.txthttp://james.newtonking.com/projects/json-net.aspxhttp://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx

  • stringdefaultJson=JsonConvert.SerializeObject(entry);//{"Details":"Applicationstarted.","LogDate":"\/Date(1234656000000)\/"}stringjavascriptJson=JsonConvert.SerializeObject(entry,//{"Details":"Applicationstarted.","LogDate":newDate(1234656000000)}stringisoJson=JsonConvert.SerializeObject(entry,//{"Details":"Applicationstarted.","LogDate":"2009-02-15T00:00:00Z"}}

    SimplypasstheJsonConverteryouwishtousetotheJson.NETserializer.

    JavaScriptDateTimeConverter

    TheJavaScriptDateTimeConverterclassisoneofthetwoDateTimeJsonConvertersthatcomewithJson.NET.ThisconverterserializesaDateTimeasaJavaScriptDateobject.

    newDate(1234656000000)

    TechnicallythisisinvalidJSONaccordingtothespecbutallbrowsers,andsomeJSONframeworksincludingJson.NET,supportit.

    IsoDateTimeConverter

    IsoDateTimeConverterseralizesaDateTimetoanISO8601formattedstring.

    "2009-02-15T00:00:00Z"

    https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Datehttp://en.wikipedia.org/wiki/ISO_8601

  • TheIsoDateTimeConverterclasshasaproperty,DateTimeFormat,tofurthercustomizetheformattedstring.

    OnefinalthingtonoteisalldatevaluesreturnedbyJson.NETareinUTCtime.

    http://en.wikipedia.org/wiki/Utc

  • Json.NET-QuickStarts&APIDocumentationSerializingCollections

    TheJsonSerializerhasgreatsupportforserializinganddeserializingcollectionsofobjects.

    Serializing

    Toserializeacollection-agenericlist,array,dictionary,oryourowncustomcollection-simplycalltheserializerwiththeobjectyouwanttogetJSONfor.Json.NETwillserializethecollectionandallofthevaluesitcontains.

    Productp1=newProduct{Name="Product1",Price=99.95m,ExpiryDate=newDateTime(2000,12,29,0,0,0,};Productp2=newProduct{Name="Product2",Price=12.50m,ExpiryDate=newDateTime(2009,7,31,0,0,0,};Listproducts=newList();products.Add(p1);products.Add(p2);stringjson=JsonConvert.SerializeObject(products,//[//{//"Name":"Product1",//"ExpiryDate":"\/Date(978048000000)\/",

  • //"Price":99.95,//"Sizes":null//},//{//"Name":"Product2",//"ExpiryDate":"\/Date(1248998400000)\/",//"Price":12.50,//"Sizes":null//}//]

    Deserializing

    TodeserializeJSONintoa.NETcollectionjustspecifythecollectiontypeyouwanttodeserializeto.Json.NETsupportsawiderangeofcollectiontypes.

    stringjson=@"[{""Name"":""Product1"",""ExpiryDate"":""\/Date(978048000000)\/"",""Price"":99.95,""Sizes"":null},{""Name"":""Product2"",""ExpiryDate"":""\/Date(1248998400000)\/"",""Price"":12.50,""Sizes"":null}]";

  • Listproducts=JsonConvert.DeserializeObject<Console.WriteLine(products.Count);//2Productp1=products[0];Console.WriteLine(p1.Name);//Product1

    DeserializingDictionaries

    UsingJson.NETyoucanalsodeserializeaJSONobjectintoa.NETgenericdictionary.TheJSONobject'spropertynamesandvalueswillbeaddedtothedictionary.

    stringjson=@"{""key1"":""value1"",""key2"":""value2""}"Dictionaryvalues=JsonConvertConsole.WriteLine(values.Count);//2Console.WriteLine(values["key1"]);//value1

  • Json.NET-QuickStarts&APIDocumentationSerializationCallbacks

    Json.NETsupportsserializationcallbackmethods.AcallbackcanbeusedtomanipulateanobjectbeforeandafteritsserializationanddeserializationbytheJsonSerializer.

    OnSerializingOnSerializedOnDeserializingOnDeserialized

    Totelltheserializerwhichmethodsshouldbecalledduringtheobject'sserializationlifecycle,decorateamethodwiththeappropraiteattribute(OnSerializingAttribute,OnSerializedAttribute,OnDeserializingAttribute,OnDeserializedAttribute).

    Exampleobjectwithserializationcallbackmethods:

    publicclassSerializationEventTestObject{//Thismemberisserializedanddeserializedwithnochange.publicintMember1{get;set;}//Thevalueofthisfieldissetandresetduringand//afterserialization.publicstringMember2{get;set;}//Thisfieldisnotserialized.TheOnDeserializedAttribute//isusedtosetthemembervalueafterserialization.[JsonIgnore]publicstringMember3{get;set;}//Thisfieldissettonull,butpopulatedafterdeserialization.publicstringMember4{get;set;}

    http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspxhttp://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializedattribute.aspxhttp://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspxhttp://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializedattribute.aspx

  • publicSerializationEventTestObject(){Member1=11;Member2="HelloWorld!";Member3="Thisisanonserializedvalue";Member4=null;}[OnSerializing]internalvoidOnSerializingMethod(StreamingContext{Member2="Thisvaluewentintothedatafileduringserialization."}[OnSerialized]internalvoidOnSerializedMethod(StreamingContext{Member2="Thisvaluewasresetafterserialization."}[OnDeserializing]internalvoidOnDeserializingMethod(StreamingContext{Member3="Thisvaluewassetduringdeserialization"}[OnDeserialized]internalvoidOnDeserializedMethod(StreamingContext{Member4="Thisvaluewassetafterdeserialization."}}

  • TheexampleobjectbeingserializedanddeserializedbyJson.NET:

    SerializationEventTestObjectobj=newSerializationEventTestObjectConsole.WriteLine(obj.Member1);//11Console.WriteLine(obj.Member2);//HelloWorld!Console.WriteLine(obj.Member3);//ThisisanonserializedvalueConsole.WriteLine(obj.Member4);//nullstringjson=JsonConvert.SerializeObject(obj,//{//"Member1":11,//"Member2":"Thisvaluewentintothedatafileduringserialization.",//"Member4":null//}Console.WriteLine(obj.Member1);//11Console.WriteLine(obj.Member2);//Thisvaluewasresetafterserialization.Console.WriteLine(obj.Member3);//ThisisanonserializedvalueConsole.WriteLine(obj.Member4);//nullobj=JsonConvert.DeserializeObject

  • //11Console.WriteLine(obj.Member2);//Thisvaluewentintothedatafileduringserialization.Console.WriteLine(obj.Member3);//ThisvaluewassetduringdeserializationConsole.WriteLine(obj.Member4);//Thisvaluewassetafterdeserialization.

  • Json.NET-QuickStarts&APIDocumentationSerializationErrorHandling

    Json.NETsupportserrorhandlingduringserializationanddeserialization.Errorhandlingletsyoucatchanerrorandchoosewhethertohandleitandcontinuewithserializationorlettheerrorbubbleupandbethrowninyourapplication.

    Errorhandlingisdefinedthroughtwomethods:theErroreventonJsonSerializerandtheOnErrorAttribute.

    ErrorEvent

    TheErroreventisaneventhandlerfoundonJsonSerializer.TheerroreventisraisedwheneveranexceptionisthrownwhileserializingordeserialingJSON.LikeallsettingsfoundonJsonSerializeritcanalsobesetonJsonSerializerSettingsandpassedtotheserializationmethodsonJsonConvert.

    Listerrors=newList();Listc=JsonConvert.DeserializeObject<""2009-09-09T00:00:00Z"",""Iamnotadateandwillerror!"",[1],""1977-02-20T00:00:00Z"",null,""2000-12-01T00:00:00Z""]",newJsonSerializerSettings{Error=delegate(objectsender,ErrorEventArgs

  • {errors.Add(args.ErrorContext.Error.Message);args.ErrorContext.Handled=true;},Converters={newIsoDateTimeConverter()}});//2009-09-09T00:00:00Z//1977-02-20T00:00:00Z//2000-12-01T00:00:00Z//ThestringwasnotrecognizedasavalidDateTime.Thereisaunknownwordstartingatindex0.//Unexpectedtokenparsingdate.ExpectedString,gotStartArray.//CannotconvertnullvaluetoSystem.DateTime.

    InthisexamplewearedeserializingaJSONarraytoacollectionofDateTimes.OntheJsonSerializerSettingsahandlerhasbeenassignedtotheErroreventwhichwilllogtheerrormessageandmarktheerrorashandled.

    TheresultofdeserializingtheJSONisthreesuccessfullydeserializeddatesandthreeerrormessages:oneforthebadlyformattedstring,"Iamnotadateandwillerror!",oneforthenestedJSONarrayandoneforthenullvaluesincethelistdoesn'tallownullableDateTimes.TheeventhandlerhasloggedthesemessagesandJson.NEThascontinuedondeserializingtheJSONbecausetheerrorsweremarkedashandled.

    OnethingtonotewitherrorhandlinginJson.NETisthatanunhandlederrorwillbubbleupandraisetheeventoneachofitsparents,e.g.anunhandlederrorwhenserializingacollectionofobjectswillberaisedtwice,onceagainsttheobjectandthenagainonthecollection.Thiswillletyouhandleanerroreitherwhereitoccurredorononeofitsparents.

  • JsonSerializerserializer=newJsonSerializerserializer.Error+=delegate(objectsender,ErrorEventArgs{//onlyloganerroronceif(args.CurrentObject==args.ErrorContext.OriginalObject)errors.Add(args.ErrorContext.Error.Message);};

    Ifyouaren'timmediatelyhandlinganerrorandonlywanttoperformanactionagainstitoncethenyoucanchecktoseewhethertheErrorEventArg'sCurrentObjectisequaltotheOriginalObject.OriginalObjectistheobjectthatthrewtheerrorandCurrentObjectistheobjectthattheeventisbeingraisedagainst.TheywillonlyequalthefirsttimetheeventisraisedagainsttheOriginalObject.

    OnErrorAttribute

    TheOnErrorAttributeworksmuchliketheother.NETserializationattributesthatJson.NETsupports.Touseityousimplyplacetheattributeonamethodwhichtakesthecorrectparameters:aStreamingContextandaErrorContext.Thenameofthemethoddoesn'tmatter.

    publicclassPersonError{privateList_roles;publicstringName{get;set;}publicintAge{get;set;}publicListRoles{get{

  • if(_roles==null)thrownewException("Rolesnotloaded!"return_roles;}set{_roles=value;}}publicstringTitle{get;set;}[OnError]internalvoidOnError(StreamingContextcontext,{errorContext.Handled=true;}}

    InthisexampleaccessingthetheRolespropertywillthrowanexceptionwhennoroleshavebeenset.TheHandleErrormethodwillsettheerrorwhenserializingRolesashandledandallowJson.NETtocontinueserializingtheclass.

    PersonErrorperson=newPersonError{Name="GeorgeMichaelBluth",Age=16,Roles=null,Title="MisterManager"};stringjson=JsonConvert.SerializeObject(person,Console.WriteLine(json);

  • //{//"Name":"GeorgeMichaelBluth",//"Age":16,//"Title":"MisterManager"//}

  • Json.NET-QuickStarts&APIDocumentationSerializationandPreservingObjectReferences

    BydefaultJson.NETwillserializeallobjectsitencountersbyvalue.IfalistcontainstwoPersonreferences,andbothreferencespointtothesameobjectthentheJsonSerializerwillwriteoutallthenamesandvaluesforeachreference.

    Personp=newPerson{BirthDate=newDateTime(1980,12,23,0,0,0,LastModified=newDateTime(2009,2,20,12,59,21,Name="James"};Listpeople=newList();people.Add(p);people.Add(p);stringjson=JsonConvert.SerializeObject(people,//[//{//"Name":"James",//"BirthDate":"\/Date(346377600000)\/",//"LastModified":"\/Date(1235134761000)\/"//},//{//"Name":"James",//"BirthDate":"\/Date(346377600000)\/",//"LastModified":"\/Date(1235134761000)\/"//}//]

  • Inmostcasesthisisthedesiredresultbutincertainscenarioswritingtheseconditeminthelistasareferencetothefirstisabettersolution.IftheaboveJSONwasdeserializednowthenthereturnedlistwouldcontaintwocompletelyseparatePersonobjectswiththesamevalues.Writingreferencesbyvaluewillalsocauseproblemsonobjectswhereacircularreferenceoccurs.

    PreserveReferencesHandling

    SettingsPreserveReferencesHandlingwilltrackobjectreferenceswhenserializinganddeserializingJSON.

    stringjson=JsonConvert.SerializeObject(people,newJsonSerializerSettings{PreserveReferencesHandling=//[//{//"$id":"1",//"Name":"James",//"BirthDate":"\/Date(346377600000)\/",//"LastModified":"\/Date(1235134761000)\/"//},//{//"$ref":"1"//}//]ListdeserializedPeople=JsonConvert.DeserializeObject<newJsonSerializerSettings{PreserveReferencesHandling=Console.WriteLine(deserializedPeople.Count);//2Personp1=deserializedPeople[0];

  • Personp2=deserializedPeople[1];Console.WriteLine(p1.Name);//JamesConsole.WriteLine(p2.Name);//Jamesboolequal=Object.ReferenceEquals(p1,p2);//true

    ThefirstPersoninthelistisserizliedwiththeadditionofanobjectId.ThesecondPersoninJSONisnowonlyareferencetothefirst.

    WithPreserveReferencesHandlingonnowonlyonePersonobjectiscreatedondeserializationandthelistcontainstworeferencestoit,mirroringwhatwestartedwith.

    IsReferenceonJsonObjectAttribute,JsonArrayAttributeandJsonPropertyAttribute

    ThePreserveReferencesHandlingsettingontheJsonSerializerwillchangehowallobjectsareserializedanddeserialized.ForfinegraincontroloverwhichobjectsandmembersshouldbeserializedasareferencethereistheIsReferencepropertyontheJsonObjectAttribute,JsonArrayAttributeandJsonPropertyAttribute.

    SettingIsReferenceonJsonObjectAttributeorJsonArrayAttributetotruewillmeantheJsonSerializerwillalwaysserializethetypetheattributeisagainstasareference.SettingIsReferenceontheJsonPropertyAttributetotruewillserializeonlythatpropertyasareference.

    [JsonObject(IsReference=true)]publicclassEmployeeReference{

  • publicstringName{get;set;}publicEmployeeReferenceManager{get;set;}}

    IReferenceResolver

    TocustomizehowreferencesaregeneratedandresolvedtheIReferenceResolverinterfaceisavailabletoinheritfromandusewiththeJsonSerializer.

  • Json.NET-QuickStarts&APIDocumentation

    CustomCreationConverter

    TheCustomCreationConverterisaJsonConverterthatprovidesawaytocustomizehowanobjectiscreatedduringJSONdeserialization.Oncetheobjecthasbeencreateditwillthenhavevaluespopulatedontoitbytheserializer.

    publicinterfaceIPerson{stringFirstName{get;set;}stringLastName{get;set;}DateTimeBirthDate{get;set;}}publicclassEmployee:IPerson{publicstringFirstName{get;set;}publicstringLastName{get;set;}publicDateTimeBirthDate{get;set;}publicstringDepartment{get;set;}publicstringJobTitle{get;set;}}publicclassPersonConverter:CustomCreationConverter{publicoverrideIPersonCreate(TypeobjectType){returnnewEmployee();}}

  • Thisisanextremelysimpleexample.Amorecomplicatedscenariocouldinvolveanobjectfactoryorservicelocatorwhichresolvestheobjectatruntime.

    //[//{//"FirstName":"Maurice",//"LastName":"Moss",//"BirthDate":"\/Date(252291661000)\/",//"Department":"IT",//"JobTitle":"Support"//},//{//"FirstName":"Jen",//"LastName":"Barber",//"BirthDate":"\/Date(258771661000)\/",//"Department":"IT",//"JobTitle":"Manager"//}//]Listpeople=JsonConvert.DeserializeObject<IPersonperson=people[0];Console.WriteLine(person.GetType());//Newtonsoft.Json.Tests.EmployeeConsole.WriteLine(person.FirstName);//MauriceEmployeeemployee=(Employee)person;

  • Console.WriteLine(employee.JobTitle);//Support

  • Json.NET-QuickStarts&APIDocumentationContractResolvers

    TheIContractResolverinterfaceprovidesawaytocustomizehowtheJsonSerializerserializesanddeserializes.NETobjectstoJSON.

    ImplementingtheIContractResolverinterfaceandthenassigninganinstancetoaJsonSerializerletsyoucontrolwhethertheobjectisserializedasaJSONobjectorJSONarray,whatobjectmembersshouldbeserialized,howtheyareserializedandwhattheyarecalled.

    DefaultContractResolver

    TheDefaultContractResolveristhedefaultresolverusedbytheserializer.Itprovidesmanyavenuesofextensibilityintheformofvirtualmethodsthatcanbeoverriden.

    CamelCasePropertyNamesContractResolver

    CamelCasePropertyNamesContractResolverinheritsfromDefaultContractResolverandsimplyoverridestheJSONpropertynametobewrittenincamelcase.

    Productproduct=newProduct{ExpiryDate=newDateTimeName="Widget",Price=9.99m,Sizes=new[]{"Small",};stringjson=JsonConvert.SerializeObject(product,Formatting.Indented,newJsonSerializerSettings{ContractResolver=

    http://en.wikipedia.org/wiki/CamelCase

  • );//{//"name":"Widget",//"expiryDate":"\/Date(1292868060000)\/",//"price":9.99,//"sizes":[//"Small",//"Medium",//"Large"//]//}

  • Json.NET-QuickStarts&APIDocumentationReducingSerializedJSONSize

    Oneofthecommonproblemsencounteredwhenserializing.NETobjectstoJSONisthattheJSONendsupcontainingalotofunwantedpropertiesandvalues.ThiscanbeespeciallyimportantwhenreturningJSONtotheclient.MoreJSONmeansmorebandwidthandaslowerwebsite.

    TosolvetheissueofunwantedJSONJson.NEThasarangeofbuiltinoptionstofinetunewhatgetswrittenfromaserializedobject.

    JsonIgnoreAttributeandDataMemberAttribute

    BydefaultJson.NETwillincludeallofaclassespublicpropertiesandfieldsintheJSONitcreates.AddingtheJsonIgnoreAttributetoapropertytellstheserializertoalwaysskipwritingittotheJSONresult.

    publicclassCar{//includedinJSONpublicstringModel{get;set;}publicDateTimeYear{get;set;}publicListFeatures{get;set;}//ignored[JsonIgnore]publicDateTimeLastModified{get;set;}}

    IfaclasshasmanypropertiesandyouonlywanttoserializeasmallsubsetofthemthenaddingJsonIgnoretoalltheotherswillbetediousanderrorprone.ThewaytotacklethisscenarioistoaddtheDataContractAttributetotheclassandDataMemberAttributestothe

    http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx

  • propertiestoserialize.Thisisopt-inserialization,onlythepropertiesyoumarkupwithbeserialized,comparedtoopt-outserializationusingJsonIgnoreAttribute.

    [DataContract]publicclassComputer{//includedinJSON[DataMember]publicstringName{get;set;}[DataMember]publicdecimalSalePrice{get;set;}//ignoredpublicstringManufacture{get;set;}publicintStockCount{get;set;}publicdecimalWholeSalePrice{get;set;}publicDateTimeNextShipmentDate{get;set;}}

    Formatting

    JSONwrittenbytheserializerwithanoptionofFormatting.Indentedproducesnicelyformatted,easytoreadJSON–greatwhenyouaredeveloping.Formatting.NoneontheotherhandkeepstheJSONresultsmall,skippingallunnecessaryspacesandlinebreakstoproducethemostcompactandefficientJSONpossible.

    NullValueHandling

    NullValueHandlingisanoptionontheJsonSerializerandcontrolshowtheserializerhandlespropertieswithanullvalue.BysettingavalueofNullValueHandling.IgnoretheJsonSerializerskipswritinganypropertiesthathaveavalueofnull.

  • publicclassMovie{publicstringName{get;set;}publicstringDescription{get;set;}publicstringClassification{get;set;}publicstringStudio{get;set;}publicDateTime?ReleaseDate{get;set;}publicListReleaseCountries{get;}

    Moviemovie=newMovie();movie.Name="BadBoysIII";movie.Description="It'snoBadBoys";stringincluded=JsonConvert.SerializeObject(movie,Formatting.Indented,newJsonSerializerSettings{});//{//"Name":"BadBoysIII",//"Description":"It'snoBadBoys",//"Classification":null,//"Studio":null,//"ReleaseDate":null,//"ReleaseCountries":null//}stringignored=JsonConvert.SerializeObject(movie,Formatting.Indented,newJsonSerializerSettings{NullValueHandling=

  • //{//"Name":"BadBoysIII",//"Description":"It'snoBadBoys"//}

    NullValueHandlingcanalsobecustomizedonindividualpropertiesusingtheaJsonPropertyAttribute.TheJsonPropertyAttributevalueofNullValueHandlingwilloverridethesettingontheJsonSerializerforthatproperty.

    DefaultValueHandling

    DefaultValueHandlingisanoptionontheJsonSerializerandcontrolshowtheserializerhandlespropertieswithadefaultvalue.SettingavalueofDefaultValueHandling.IgnorewillmaketheJsonSerializerskipwritinganypropertiesthathaveadefaultvaluetotheJSONresult.Forobjectreferencesthiswillbenull.ForvaluetypeslikeintandDateTimetheserializerwillskipthedefaultunitializedvalueforthatvaluetype.

    Json.NETalsoallowsyoutocustomizewhatthedefaultvalueofanindividualpropertyisusingtheDefaultValueAttribute.ForexampleifastringpropertycalledDepartmentalwaysreturnsanemptystringinitsdefaultstateandyoudidn'twantthatemptystringinyourJSONthenplacingtheDefaultValueAttributeonDepartmentwiththatvaluewillmeanDepartmentisnolongerwrittentoJSONunlessithasavalue.

    publicclassInvoice{publicstringCompany{get;set;}publicdecimalAmount{get;set;}//falseisdefaultvalueofboolpublicboolPaid{get;set;}//nullisdefaultvalueofnullablepublicDateTime?PaidDate{get;set;}

    http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

  • //customizedefaultvalues[DefaultValue(30)]publicintFollowUpDays{get;set;}[DefaultValue("")]publicstringFollowUpEmailAddress{get;set}

    Invoiceinvoice=newInvoice{Company="AcmeLtd.",Amount=50.0m,Paid=false,FollowUpDays=30,FollowUpEmailAddress=string.Empty,PaidDate=null};stringincluded=JsonConvert.SerializeObject(invoice,Formatting.Indented,newJsonSerializerSettings{});//{//"Company":"AcmeLtd.",//"Amount":50.0,//"Paid":false,//"PaidDate":null,//"FollowUpDays":30,//"FollowUpEmailAddress":""//}

  • stringignored=JsonConvert.SerializeObject(invoice,Formatting.Indented,newJsonSerializerSettings{DefaultValueHandling=//{//"Company":"AcmeLtd.",//"Amount":50.0//}

    DefaultValueHandlingcanalsobecustomizedonindividualpropertiesusingtheaJsonPropertyAttribute.TheJsonPropertyAttributevalueofDefaultValueHandlingwilloverridethesettingontheJsonSerializerforthatproperty.

    IContractResolver

    FormoreflexibilitytheIContractResolverprovidesaninterfacetocustomizealmosteveryaspectofhowa.NETobjectgetsserializedtoJSON,includingchangingserializationbehavioratruntime.

    publicclassDynamicContractResolver:DefaultContractResolver{privatereadonlychar_startingWithChar;publicDynamicContractResolver(charstartingWithChar){_startingWithChar=startingWithChar;}protectedoverrideIListCreateProperties({IListproperties=base.CreateProperties(contract);//onlyserializerpropertiesthatstartwiththespecifiedcharacter

  • properties=properties.Where(p=>p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();returnproperties;}}publicclassBook{publicstringBookName{get;set;}publicdecimalBookPrice{get;set;}publicstringAuthorName{get;set;}publicintAuthorAge{get;set;}publicstringAuthorCountry{get;set;}}

    Bookbook=newBook{BookName="TheGatheringStorm"BookPrice=16.19m,AuthorName="BrandonSanderson"AuthorAge=34,AuthorCountry="UnitedStatesofAmerica"};stringstartingWithA=JsonConvert.SerializeObject(book,newJsonSerializerSettings{ContractResolver=//{//"AuthorName":"BrandonSanderson",//"AuthorAge":34,

  • //"AuthorCountry":"UnitedStatesofAmerica"//}stringstartingWithB=JsonConvert.SerializeObject(book,newJsonSerializerSettings{ContractResolver=//{//"BookName":"TheGatheringStorm",//"BookPrice":16.19//}

  • Json.NET-QuickStarts&APIDocumentationSerializingPartialJSONFragments

    OftenwhenworkingwithlargeJSONdocumentsyou'reonlyinterestedinasmallfragmentofinformation.ThisscenariocanbeannoyingwhenyouwanttoserializethatJson.NETinto.NETobjectsbecauseyouhavetodefine.NETclassesfortheentireJSONresult.

    WithJson.NETitiseasytogetaroundthisproblem.UsingLINQtoJSONyoucanextractthepiecesofJSONyouwanttoserializebeforepassingthemtotheJson.NETserializer.

    publicclassSearchResult{publicstringTitle{get;set;}publicstringContent{get;set;}publicstringUrl{get;set;}}

    stringgoogleSearchText=@"{""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"":""ParisHilton-Wikipedia,thefreeencyclopedia"",""titleNoFormatting"":""ParisHilton-Wikipedia,thefreeencyclopedia"",""content"":""[1]In2006,shereleasedherdebutalbum...""},{

  • ""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"":""ParisHilton"",""titleNoFormatting"":""ParisHilton"",""content"":""Self:Zoolander.SocialiteParisHilton...""}],""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}";JObjectgoogleSearch=JObject.Parse(googleSearchText);//getJSONresultobjectsintoalistIListresults=googleSearch["responseData"//serializeJSONresultsinto.NETobjectsIListsearchResults=newList

  • Json.NET-QuickStarts&APIDocumentationLINQtoJSON

    LINQtoJSONisaprogrammingAPIforworkingwithJSONobjects.TheAPIhasbeendesignedwithLINQinmindtoenabletoquickqueryingandcreationofJSONobjects.LINQtoJSONsitsundertheNewtonsoft.Json.Linqnamespace.

    CreatingJSON

    ThereareanumberofdifferentoptionswhenitcomestocreatingJSONusingLINQtoJSON.Thefirsttocreateobjectsimperatively.Youhavetotalcontrolbutitismoreverbosethanotheroptions.

    JArrayarray=newJArray();JValuetext=newJValue("Manualtext");JValuedate=newJValue(newDateTime(2000,5,23));array.Add(text);array.Add(date);stringjson=array.ToString();//[//"Manualtext",//"\/Date(958996800000+1200)\/"//]

    AnotheroptionistocreateJSONobjectsdeclaratively.

    Listposts=GetPosts();JObjectrss=newJObject(newJProperty("channel",

  • newJObject(newJProperty("title","JamesNewton-King"newJProperty("link","http://james.newtonking.com"newJProperty("description","JamesNewton-King'sblog."newJProperty("item",newJArray(frompinpostsorderbyp.TitleselectnewJObject(newJProperty("title",p.Title),newJProperty("description",p.Description),newJProperty("link",p.Link),newJProperty("category",newJArray(fromcinp.CategoriesselectnewJValue(c)))))))));Console.WriteLine(rss.ToString());//{//"channel":{//"title":"JamesNewton-King",//"link":"http://james.newtonking.com",//"description":"JamesNewton-King'sblog.",//"item":[//{//"title":"Json.NET1.3+Newlicense+NowonCodePlex",//"description":"AnnoucingthereleaseofJson.NET1.3,theMITlicenseandthesourcebeingavailableonCodePlex",//"link":"http://james.newtonking.com/projects/json-net.aspx",//"category":[//"Json.NET",//"CodePlex"//]

  • //},//{//"title":"LINQtoJSONbeta",//"description":"AnnoucingLINQtoJSON",//"link":"http://james.newtonking.com/projects/json-net.aspx",//"category":[//"Json.NET",//"LINQ"//]//}//]//}//}

    YoucancreateaJSONobjectfromanon-JSONtypeusingtheFromObjectmethod.

    JObjecto=JObject.FromObject(new{channel=new{title="JamesNewton-King",link="http://james.newtonking.com",description="JamesNewton-King'sblog.",item=frompinpostsorderbyp.Titleselectnew{title=p.Title,description=p.Description,link=p.Link,

  • category=p.Categories}}});

    FinallyJSONobjectscanbecreatedfromastringusetheParsemethod.

    stringjson=@"{CPU:'Intel',Drives:['DVDread/writer',""500gigabyteharddrive""]}";JObjecto=JObject.Parse(json);

    QueryingJSON

    ThepropertiesmethodsthatarethemostusefulwhenqueryingJSONobjectsaretheChildrenmethodandthepropertyindex.

    Childrenreturnsallthechildrenofthatobject.IfitisaJObjectitwillreturnacollectionofpropertiestoworkwithandifitisaJArrayyouwillgetacollectionofthearray'svalues.

    Thepropertyindexisusedtogetaspecificchild,eitherbyindexpositionforJSONarraysorpropertynameforJSONobjects.

    varpostTitles=frompinrss["channel"]["item"].Children()select(string)p["title"];

  • foreach(variteminpostTitles){Console.WriteLine(item);}//LINQtoJSONbeta//Json.NET1.3+Newlicense+NowonCodePlexvarcategories=fromcinrss["channel"]["item"].Children()[groupcbycintogorderbyg.Count()descendingselectnew{Category=g.Key,Count=g.Count()};foreach(varcincategories){Console.WriteLine(c.Category+"-Count:"+c.Count);}//Json.NET-Count:2//LINQ-Count:1//CodePlex-Count:1

    LINQtoJSONcanalsobeusedtomanuallyconvertfromJSONtoa.NETobject.

    publicclassShortie{publicstringOriginal{get;set;}publicstringShortened{get;set;}publicstringShort{get;set;}

  • publicShortieExceptionError{get;set;}}publicclassShortieException{publicintCode{get;set;}publicstringErrorMessage{get;set;}}

    Manuallyserializinganddeserializingbetween.NETobjectsismostusefulwhenworkingwithJSONthatdoesn'tcloselymatchyour.NETobjects.

    stringjsonText=@"{""short"":{""original"":""http://www.foo.com/"",""short"":""krehqk"",""error"":{""code"":0,""msg"":""Noactiontaken""}}";JObjectjson=JObject.Parse(jsonText);Shortieshortie=newShortie{Original=(string)json["short"Short=(string)json["short"Error=newShortieException{Code=(int)json[ErrorMessage=(

  • }};Console.WriteLine(shortie.Original);//http://www.foo.com/Console.WriteLine(shortie.Error.ErrorMessage);//Noactiontaken

  • Json.NET-QuickStarts&APIDocumentationQueryingLINQtoJSONwithSelectToken

    SelectTokenprovidesamethodtoqueryLINQtoJSONusingasinglestringpathtoadesiredJToken.SelectTokenmakesdynamicquerieseasybecausetheentirequeryisdefinedinastring.

    stringname=(string)o.SelectToken("Manufacturers[0].Name"

    SelectToken

    SelectTokenisamethodonJTokenandtakesastringpathtoachildtoken.SelectTokenreturnsthechildtokenoranullreferenceifatokencouldn'tbefoundatthepath'slocation.

    Thepathismadeupofpropertynamesandarrayindexesseparatedbyperiods.Arrayindexescanuseeithersquareorroundbrackets.Bothofthefollowingarevalidpathsandareequivalenttoeachother:Manufacturers[0].NameandManufacturers(0).Name.

    JObjecto=JObject.Parse(@"{""Stores"":[""LambtonQuay"",""WillisStreet""],""Manufacturers"":[{""Name"":""AcmeCo"",""Products"":[{""Name"":""Anvil"",""Price"":50}

  • ]},{""Name"":""Contoso"",""Products"":[{""Name"":""ElbowGrease"",""Price"":99.95},{""Name"":""HeadlightFluid"",""Price"":4}]}]}");stringname=(string)o.SelectToken("Manufacturers[0].Name"//AcmeCodecimalproductPrice=(decimal)o.SelectToken(//50stringproductName=(string)o.SelectToken("Manufacturers[1].Products[0].Name"//ElbowGrease

    SelectTokenwithLINQ

    SelectTokencanbeusedincombinationwithstandardLINQmethods.

    IListstoreNames=o.SelectToken("Stores"

  • //LambtonQuay//WillisStreetIListfirstProductNames=o["Manufacturers"//null//HeadlightFluiddecimaltotalPrice=o["Manufacturers"].Sum(m=>(//149.95

  • Json.NET-QuickStarts&APIDocumentationReadingandWritingJSON

    TomanuallyreadandwriteJSONJson.NETprovidestheJsonReaderandJsonWriterclasses.

    JsonTextReaderandJsonTextWriter

    JsonTextReaderandJsonTextWriterareusedtoreadandwriteJSONtext.TheJsonTextWriterhasanumberofsettingsonittocontrolhowJSONisformattedwhenitiswritten.Theseoptionsincludeformatting,indentioncharacter,indentcountandquotecharacter.

    StringBuildersb=newStringBuilder();StringWritersw=newStringWriter(sb);using(JsonWriterjsonWriter=newJsonTextWriter{jsonWriter.Formatting=Formatting.Indented;jsonWriter.WriteStartObject();jsonWriter.WritePropertyName("CPU");jsonWriter.WriteValue("Intel");jsonWriter.WritePropertyName("PSU");jsonWriter.WriteValue("500W");jsonWriter.WritePropertyName("Drives");jsonWriter.WriteStartArray();jsonWriter.WriteValue("DVDread/writer");jsonWriter.WriteComment("(broken)");jsonWriter.WriteValue("500gigabyteharddrive"jsonWriter.WriteValue("200gigabypeharddrive"jsonWriter.WriteEnd();jsonWriter.WriteEndObject();

  • }//{//"CPU":"Intel",//"PSU":"500W",//"Drives":[//"DVDread/writer"///*(broken)*/,//"500gigabyteharddrive",//"200gigabypeharddrive"//]//}

    JTokenReaderandJTokenWriter

    JTokenReaderandJTokenWriterreadandwriteLINQtoJSONobjects.TheyarelocatedintheNewtonsoft.Json.Linqnamespace.TheseobjectsallowyoutouseLINQtoJSONobjectswithobjectsthatreadandwriteJSONsuchastheJsonSerializer.ForexampleyoucandeserializefromaLINQtoJSONobjectintoaregular.NETobjectandviceversa.

    JObjecto=newJObject(newJProperty("Name","JohnSmith"),newJProperty("BirthDate",newDateTime(1983,3,20)));JsonSerializerserializer=newJsonSerializerPersonp=(Person)serializer.Deserialize(newConsole.WriteLine(p.Name);//JohnSmith

  • Json.NET-QuickStarts&APIDocumentationConvertingbetweenJSONandXML

    Json.NETsupportsconvertingJSONtoXMLandviceversausingtheXmlNodeConverter.

    Elements,attributes,text,comments,characterdata,processinginstructions,namespacesandtheXMLdeclarationareallpreservedwhenconvertingbetweenthetwo.Theonlycaveatisthatitispossibletolosetheorderofdifferentlynamednodesatthesamelevelwhentheyaregroupedtogetherintoanarray.

    ConversionRules

    Elementsremainunchanged.Attributesareprefixedwithan@.Singlechildtextnodesareavaluedirectlyagainstanelement,otherwisetheyareaccessedvia#text.TheXMLdeclarationandprocessinginstructionsareprefixedwith?.Charaterdata,comments,whitespaceandsignificatewhitespacenodesareaccessedvia#cdata-section,#comment,#whitespaceand#significate-whitespacerespectively.Multiplenodeswiththesamenameatthesamelevelaregroupedtogetherintoanarray.Emptyelementsarenull.

    SerializeXmlNode

    TheJsonConverthastwohelpermethodsforconvertingbetweenJSONandXML.ThefirstisSerializeXmlNode.ThismethodtakesanXmlNodeandserializesittoJSONtext.

    stringxml=@"

  • Alanhttp://www.google.comLouishttp://www.yahoo.com";XmlDocumentdoc=newXmlDocument();doc.LoadXml(xml);stringjsonText=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"//}//]//}//}

  • DeserializeXmlNode

    ThesecondhelpermethodonJsonConvertisDeserializeXmlNode.ThismethodtakesJSONtextanddeserializesitintoaXmlNode.

    BecausevalidXMLmusthaveonerootelementtheJSONpassedtoDeserializeXmlNodeshouldhaveonepropertyintherootJSONobject.IftherootJSONobjecthasmultiplepropertiesthentheoverloadthatalsotakesanelementnameshouldbeused.ArootelementwiththatnamewillbeinsertedintothedeserializedXmlNode.

    stringjson=@"{""?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""}]}}";

  • XmlDocumentdoc=(XmlDocument)JsonConvert.DeserializeXmlNode(json);////////Alan//http://www.google.com//////Louis//http://www.yahoo.com////

  • C#Namespaces►Newtonsoft.Json

    Json.NET-QuickStarts&APIDocumentationNewtonsoft.JsonNamespace

    TheNewtonsoft.Jsonnamespaceprovidesclassesthatareusedtoimplementthecoreservicesoftheframework.

    DeclarationSyntaxC# VisualBasic VisualC++

    namespaceNewtonsoft.Json

    NamespaceNewtonsoft.Json

    namespaceNewtonsoft.Json

    TypesAllTypes Classes Interfaces Enumerations

    Icon Type DescriptionConstructorHandling Specifieshowconstructorsare

    usedwheninitializingobjectsduringdeserializationbytheJsonSerializer.

    DefaultValueHandling SpecifiesdefaultvaluehandlingoptionsfortheJsonSerializer.

    Formatting SpecifiesformattingoptionsfortheJsonTextWriter.

    IJsonLineInfo Providesaninterfacetoenablea

  • classtoreturnlineandpositioninformation.

    JsonArrayAttribute InstructstheJsonSerializerhowtoserializethecollection.

    JsonConstructorAttribute InstructstheJsonSerializernottoserializethepublicfieldorpublicread/writepropertyvalue.

    JsonContainerAttribute InstructstheJsonSerializerhowtoserializetheobject.

    JsonConvert ProvidesmethodsforconvertingbetweencommonlanguageruntimetypesandJSONtypes.

    JsonConverter ConvertsanobjecttoandfromJSON.

    JsonConverterAttribute InstructstheJsonSerializertousethespecifiedJsonConverterwhenserializingthememberorclass.

    JsonConverterCollection RepresentsacollectionofJsonConverter.

  • JsonIgnoreAttribute InstructstheJsonSerializernottoserializethepublicfieldorpublicread/writepropertyvalue.

    JsonObjectAttribute InstructstheJsonSerializerhowtoserializetheobject.

    JsonPropertyAttribute InstructstheJsonSerializertoalwaysserializethememberwiththespecifiedname.

    JsonReader Representsareaderthatprovidesfast,non-cached,forward-onlyaccesstoserializedJsondata.

    JsonReaderException TheexceptionthrownwhenanerroroccurswhilereadingJsontext.

    JsonSerializationException TheexceptionthrownwhenanerroroccursduringJsonserializationordeserialization.

    JsonSerializer SerializesanddeserializesobjectsintoandfromtheJSONformat.TheJsonSerializerenablesyoutocontrolhowobjectsareencodedintoJSON.

  • JsonSerializerSettings SpecifiesthesettingsonaJsonSerializerobject.

    JsonTextReader Representsareaderthatprovidesfast,non-cached,forward-onlyaccesstoserializedJsondata.

    JsonTextWriter Representsawriterthatprovidesafast,non-cached,forward-onlywayofgeneratingJsondata.

    JsonToken SpecifiesthetypeofJsontoken.

    JsonValidatingReader RepresentsareaderthatprovidesJsonSchemavalidation.

    JsonWriter Representsawriterthatprovidesafast,non-cached,forward-onlywayofgeneratingJsondata.

    JsonWriterException TheexceptionthrownwhenanerroroccurswhilereadingJsontext.

    MemberSerialization SpecifiesthememberserializationoptionsfortheJsonSerializer.

  • MissingMemberHandling SpecifiesmissingmemberhandlingoptionsfortheJsonSerializer.

    NullValueHandling SpecifiesnullvaluehandlingoptionsfortheJsonSerializer.

    ObjectCreationHandling SpecifieshowobjectcreationishandledbytheJsonSerializer.

    PreserveReferencesHandling SpecifiesreferencehandlingoptionsfortheJsonSerializer.

    ReferenceLoopHandling SpecifiesreferenceloophandlingoptionsfortheJsonSerializer.

    Required Indicatingwhetherapropertyisrequired.

    JsonReader.State Specifiesthestateofthereader.

    TypeNameHandling SpecifiestypenamehandlingoptionsfortheJsonSerializer.

    WriteState Specifiesthestateofthe

  • JsonWriter.

  • Namespaces►Newtonsoft.Json►ConstructorHandlingC#

    Json.NET-QuickStarts&APIDocumentationConstructorHandlingEnumeration

    SpecifieshowconstructorsareusedwheninitializingobjectsduringdeserializationbytheJsonSerializer.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicenumConstructorHandling

    PublicEnumerationConstructorHandling

    publicenumclassConstructorHandling

    MembersMember DescriptionDefault Firstattempttousethepublic

    defaultconstructorthenfallbacktosingleparamatizedconstructor.

    AllowNonPublicDefaultConstructor AllowJson.NETtouseanon-publicdefaultconstructor.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►DefaultValueHandlingC#

    Json.NET-QuickStarts&APIDocumentationDefaultValueHandlingEnumeration

    SpecifiesdefaultvaluehandlingoptionsfortheJsonSerializer.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicenumDefaultValueHandling

    PublicEnumerationDefaultValueHandling

    publicenumclassDefaultValueHandling

    MembersMember DescriptionInclude Includedefaultvalueswhenserializing

    anddeserializingobjects.

    Ignore Ignoredefaultvalueswhenserializinganddeserializingobjects.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • C#Namespaces►Newtonsoft.Json►FormattingJson.NET-QuickStarts&APIDocumentationFormattingEnumeration

    SpecifiesformattingoptionsfortheJsonTextWriter.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicenumFormatting

    PublicEnumerationFormatting

    publicenumclassFormatting

    MembersMember DescriptionNone Nospecialformattingisapplied.Thisis

    thedefault.

    Indented CauseschildobjectstobeindentedaccordingtotheIndentationandIndentCharsettings.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • C#Namespaces►Newtonsoft.Json►IJsonLineInfoJson.NET-QuickStarts&APIDocumentationIJsonLineInfoInterface

    Providesaninterfacetoenableaclasstoreturnlineandpositioninformation.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicinterfaceIJsonLineInfo

    PublicInterfaceIJsonLineInfo

    publicinterfaceclassIJsonLineInfo

    MembersAllMembers Methods Properties

    PublicProtected

    InstanceStatic

    Declared

    InheritedIcon Member Description

    HasLineInfo() Getsavalueindicatingwhethertheclasscanreturnlineinformation.

    LineNumber Getsthecurrentlinenumber.

    LinePosition Getsthecurrentlineposition.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0

  • (4.0.2.13623)

  • Namespaces►Newtonsoft.Json►IJsonLineInfo►HasLineInfo()C#

    Json.NET-QuickStarts&APIDocumentationHasLineInfoMethod

    Getsavalueindicatingwhethertheclasscanreturnlineinformation.

    DeclarationSyntaxC# VisualBasic VisualC++

    boolHasLineInfo()

    FunctionHasLineInfoAsBoolean

    boolHasLineInfo()

    ReturnValuetrueifLineNumberandLinePositioncanbeprovided;otherwise,false.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50

  • Namespaces►Newtonsoft.Json►IJsonLineInfo►LineNumberC#

    Json.NET-QuickStarts&APIDocumentationLineNumberProperty

    Getsthecurrentlinenumber.

    DeclarationSyntaxC# VisualBasic VisualC++

    intLineNumber{get;}

    ReadOnlyPropertyLineNumberAsInteger Get

    propertyintLineNumber{ intget();}

    ValueThecurrentlinenumberor0ifnolineinformationisavailable(forexample,HasLineInforeturnsfalse).

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409d

  • Namespaces►Newtonsoft.Json►IJsonLineInfo►LinePositionC#

    Json.NET-QuickStarts&APIDocumentationLinePositionProperty

    Getsthecurrentlineposition.

    DeclarationSyntaxC# VisualBasic VisualC++

    intLinePosition{get;}

    ReadOnlyPropertyLinePositionAsInteger Get

    propertyintLinePosition{ intget();}

    ValueThecurrentlinepositionor0ifnolineinformationisavailable(forexample,HasLineInforeturnsfalse).

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409d

  • C#Namespaces►Newtonsoft.Json►JsonArrayAttributeJson.NET-QuickStarts&APIDocumentationJsonArrayAttributeClass

    InstructstheJsonSerializerhowtoserializethecollection.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicsealedclassJsonArrayAttribute:JsonContainerAttribute

    PublicNotInheritableClassJsonArrayAttribute_ InheritsJsonContainerAttribute

    publicrefclassJsonArrayAttributesealed:public

    MembersAllMembers Constructors Methods Properties

    PublicProtected

    InstanceStatic

    Declared

    InheritedIcon Member Description

    JsonArrayAttribute() InitializesanewinstanceoftheJsonArrayAttributeclass.

    JsonArrayAttribute(Boolean) InitializesanewinstanceoftheJsonObjectAttributeclasswithaflagindicatingwhetherthearraycancontainnullitems

    JsonArrayAttribute(String) InitializesanewinstanceoftheJsonArrayAttributeclasswiththespecifiedcontainerId.

  • AllowNullItems Getsorsetsavalueindicatingwhethernullitemsareallowedinthecollection.

    Description Getsorsetsthedescription.

    (InheritedfromJsonContainerAttribute.)

    Equals(Object) Returnsavaluethatindicateswhetherthisinstanceisequaltoaspecifiedobject.

    (InheritedfromAttribute.)

    Finalize() AllowsanObjecttoattempttofreeresourcesandperformothercleanupoperationsbeforetheObjectisreclaimedbygarbagecollection.

    (InheritedfromObject.)

    GetHashCode() Returnsthehashcodeforthisinstance.

    (InheritedfromAttribute.)

    GetType() GetstheTypeofthecurrentinstance.

    (InheritedfromObject.)

    Id Getsorsetstheid.

    (InheritedfromJsonContainerAttribute.)

    IsDefaultAttribute() Whenoverriddeninaderivedclass,indicateswhetherthevalueofthis

    http://msdn2.microsoft.com/en-us/library/09ds241whttp://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/4k87zsw7http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/365e1bxshttp://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/dfwy45w9http://msdn2.microsoft.com/en-us/library/42892f65http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/tbkb5x6t

  • instanceisthedefaultvalueforthederivedclass.

    (InheritedfromAttribute.)

    IsReference Getsorsetsavaluethatindicateswhethertopreserveobjectreferencedata.

    (InheritedfromJsonContainerAttribute.)

    Match(Object) Whenoverriddeninaderivedclass,returnsavaluethatindicateswhetherthisinstanceequalsaspecifiedobject.

    (InheritedfromAttribute.)

    MemberwiseClone() CreatesashallowcopyofthecurrentObject.

    (InheritedfromObject.)

    Title Getsorsetsthetitle.

    (InheritedfromJsonContainerAttribute.)

    ToString() ReturnsaStringthatrepresentsthecurrentObject.

    (InheritedfromObject.)

    TypeId Whenimplementedinaderivedclass,getsauniqueidentifierforthisAttribute.

    (InheritedfromAttribute.)

    InheritanceHierarchyObject

    http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/wy7chz44http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/57ctke0ahttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/7bxwbwt2http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/sa1bf03ehttp://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/e5kfa45b

  • Attribute

    JsonContainerAttribute JsonArrayAttribute

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/e8kc3626

  • Namespaces►Newtonsoft.Json►JsonArrayAttribute►JsonArrayAttribute()

    C#

    Json.NET-QuickStarts&APIDocumentationJsonArrayAttributeConstructor

    MembersIcon Member Description

    JsonArrayAttribute() InitializesanewinstanceoftheJsonArrayAttributeclass.

    JsonArrayAttribute(Boolean) InitializesanewinstanceoftheJsonObjectAttributeclasswithaflagindicatingwhetherthearraycancontainnullitems

    JsonArrayAttribute(String) InitializesanewinstanceoftheJsonArrayAttributeclasswiththespecifiedcontainerId.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonArrayAttribute►JsonArrayAttribute()

    C#

    Json.NET-QuickStarts&APIDocumentationJsonArrayAttributeConstructor

    InitializesanewinstanceoftheJsonArrayAttributeclass.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicJsonArrayAttribute()

    PublicSubNew

    public:JsonArrayAttribute()

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonArrayAttribute►JsonArrayAttribute(Boolean)

    C#

    Json.NET-QuickStarts&APIDocumentationJsonArrayAttributeConstructor(allowNullItems)

    InitializesanewinstanceoftheJsonObjectAttributeclasswithaflagindicatingwhetherthearraycancontainnullitems

    DeclarationSyntaxC# VisualBasic VisualC++

    publicJsonArrayAttribute( boolallowNullItems)

    PublicSubNew(_ allowNullItemsAsBoolean_)

    public:JsonArrayAttribute( boolallowNullItems)

    ParametersallowNullItems(Boolean)

    Aflagindicatingwhetherthearraycancontainnullitems.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50

  • Namespaces►Newtonsoft.Json►JsonArrayAttribute►JsonArrayAttribute(String)

    C#

    Json.NET-QuickStarts&APIDocumentationJsonArrayAttributeConstructor(id)

    InitializesanewinstanceoftheJsonArrayAttributeclasswiththespecifiedcontainerId.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicJsonArrayAttribute( stringid)

    PublicSubNew(_ idAsString_)

    public:JsonArrayAttribute( String^id)

    Parametersid(String)

    ThecontainerId.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • Namespaces►Newtonsoft.Json►JsonArrayAttribute►AllowNullItems

    C#

    Json.NET-QuickStarts&APIDocumentationAllowNullItemsProperty

    Getsorsetsavalueindicatingwhethernullitemsareallowedinthecollection.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicboolAllowNullItems{get;set;}

    PublicPropertyAllowNullItemsAsBoolean Get Set

    public:propertyboolAllowNullItems{ boolget(); voidset(boolvalue);}

    Valuetrueifnullitemsareallowedinthecollection;otherwise,false.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50

  • Namespaces►Newtonsoft.Json►JsonConstructorAttributeC#

    Json.NET-QuickStarts&APIDocumentationJsonConstructorAttributeClass

    InstructstheJsonSerializernottoserializethepublicfieldorpublicread/writepropertyvalue.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicsealedclassJsonConstructorAttribute:Attribute

    PublicNotInheritableClassJsonConstructorAttribute InheritsAttribute

    publicrefclassJsonConstructorAttributesealed:public

    MembersAllMembers Constructors Methods Properties

    PublicProtected

    InstanceStatic

    Declared

    InheritedIcon Member Description

    JsonConstructorAttribute() InitializesanewinstanceoftheJsonConstructorAttributeclass

    Equals(Object) Returnsavaluethatindicateswhetherthisinstanceisequaltoaspecifiedobject.

    (InheritedfromAttribute.)

    Finalize() AllowsanObjecttoattempttofree

    http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/09ds241whttp://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/4k87zsw7http://msdn2.microsoft.com/en-us/library/e5kfa45b

  • resourcesandperformothercleanupoperationsbeforetheObjectisreclaimedbygarbagecollection.

    (InheritedfromObject.)

    GetHashCode() Returnsthehashcodeforthisinstance.

    (InheritedfromAttribute.)

    GetType() GetstheTypeofthecurrentinstance.

    (InheritedfromObject.)

    IsDefaultAttribute() Whenoverriddeninaderivedclass,indicateswhetherthevalueofthisinstanceisthedefaultvalueforthederivedclass.

    (InheritedfromAttribute.)

    Match(Object) Whenoverriddeninaderivedclass,returnsavaluethatindicateswhetherthisinstanceequalsaspecifiedobject.

    (InheritedfromAttribute.)

    MemberwiseClone() CreatesashallowcopyofthecurrentObject.

    (InheritedfromObject.)

    ToString() ReturnsaStringthatrepresentsthecurrentObject.

    (InheritedfromObject.)

    TypeId Whenimplementedinaderivedclass,getsauniqueidentifierforthisAttribute.

    http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/365e1bxshttp://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/dfwy45w9http://msdn2.microsoft.com/en-us/library/42892f65http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/tbkb5x6thttp://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/wy7chz44http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/57ctke0ahttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/7bxwbwt2http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/sa1bf03ehttp://msdn2.microsoft.com/en-us/library/e8kc3626

  • (InheritedfromAttribute.)

    InheritanceHierarchyObjectAttribute

    JsonConstructorAttribute

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e8kc3626

  • Namespaces►Newtonsoft.Json►JsonConstructorAttribute►JsonConstructorAttribute()

    C#

    Json.NET-QuickStarts&APIDocumentationJsonConstructorAttributeConstructor

    InitializesanewinstanceoftheJsonConstructorAttributeclass

    DeclarationSyntaxC# VisualBasic VisualC++

    publicJsonConstructorAttribute()

    PublicSubNew

    public:JsonConstructorAttribute()

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonContainerAttributeC#

    Json.NET-QuickStarts&APIDocumentationJsonContainerAttributeClass

    InstructstheJsonSerializerhowtoserializetheobject.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicabstractclassJsonContainerAttribute:Attribute

    PublicMustInheritClassJsonContainerAttribute_ InheritsAttribute

    publicrefclassJsonContainerAttributeabstract:public

    MembersAllMembers Constructors Methods Properties

    PublicProtected

    InstanceStatic

    Declared

    InheritedIcon Member Description

    JsonContainerAttribute() InitializesanewinstanceoftheJsonContainerAttributeclass.

    JsonContainerAttribute(String) InitializesanewinstanceoftheJsonContainerAttributeclasswiththespecifiedcontainerId.

    Description Getsorsetsthedescription.

    http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/e8kc3626

  • Equals(Object) Returnsavaluethatindicateswhetherthisinstanceisequaltoaspecifiedobject.

    (InheritedfromAttribute.)

    Finalize() AllowsanObjecttoattempttofreeresourcesandperformothercleanupoperationsbeforetheObjectisreclaimedbygarbagecollection.

    (InheritedfromObject.)

    GetHashCode() Returnsthehashcodeforthisinstance.

    (InheritedfromAttribute.)

    GetType() GetstheTypeofthecurrentinstance.

    (InheritedfromObject.)

    Id Getsorsetstheid.

    IsDefaultAttribute() Whenoverriddeninaderivedclass,indicateswhetherthevalueofthisinstanceisthedefaultvalueforthederivedclass.

    (InheritedfromAttribute.)

    IsReference Getsorsetsavaluethatindicateswhethertopreserveobjectreferencedata.

    Match(Object) Whenoverriddeninaderived

    http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/09ds241whttp://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/4k87zsw7http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/365e1bxshttp://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/dfwy45w9http://msdn2.microsoft.com/en-us/library/42892f65http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/tbkb5x6thttp://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/wy7chz44

  • class,returnsavaluethatindicateswhetherthisinstanceequalsaspecifiedobject.

    (InheritedfromAttribute.)

    MemberwiseClone() CreatesashallowcopyofthecurrentObject.

    (InheritedfromObject.)

    Title Getsorsetsthetitle.

    ToString() ReturnsaStringthatrepresentsthecurrentObject.

    (InheritedfromObject.)

    TypeId Whenimplementedinaderivedclass,getsauniqueidentifierforthisAttribute.

    (InheritedfromAttribute.)

    InheritanceHierarchyObjectAttribute

    JsonContainerAttribute JsonArrayAttribute JsonObjectAttribute

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/57ctke0ahttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/7bxwbwt2http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/sa1bf03ehttp://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/e8kc3626http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e8kc3626

  • Namespaces►Newtonsoft.Json►JsonContainerAttribute►JsonContainerAttribute()

    C#

    Json.NET-QuickStarts&APIDocumentationJsonContainerAttributeConstructor

    MembersIcon Member Description

    JsonContainerAttribute() InitializesanewinstanceoftheJsonContainerAttributeclass.

    JsonContainerAttribute(String) InitializesanewinstanceoftheJsonContainerAttributeclasswiththespecifiedcontainerId.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonContainerAttribute►JsonContainerAttribute()

    C#

    Json.NET-QuickStarts&APIDocumentationJsonContainerAttributeConstructor

    InitializesanewinstanceoftheJsonContainerAttributeclass.

    DeclarationSyntaxC# VisualBasic VisualC++

    protectedJsonContainerAttribute()

    ProtectedSubNew

    protected:JsonContainerAttribute()

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonContainerAttribute►JsonContainerAttribute(String)

    C#

    Json.NET-QuickStarts&APIDocumentationJsonContainerAttributeConstructor(id)

    InitializesanewinstanceoftheJsonContainerAttributeclasswiththespecifiedcontainerId.

    DeclarationSyntaxC# VisualBasic VisualC++

    protectedJsonContainerAttribute( stringid)

    ProtectedSubNew(_ idAsString_)

    protected:JsonContainerAttribute( String^id)

    Parametersid(String)

    ThecontainerId.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • Namespaces►Newtonsoft.Json►JsonContainerAttribute►Description

    C#

    Json.NET-QuickStarts&APIDocumentationDescriptionProperty

    Getsorsetsthedescription.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstringDescription{get;set;}

    PublicPropertyDescriptionAsString Get Set

    public:propertyString^Description{ String^get(); voidset(String^value);}

    ValueThedescription.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • Namespaces►Newtonsoft.Json►JsonContainerAttribute►IdC#

    Json.NET-QuickStarts&APIDocumentationIdProperty

    Getsorsetstheid.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstringId{get;set;}

    PublicPropertyIdAsString Get Set

    public:propertyString^Id{ String^get(); voidset(String^value);}

    ValueTheid.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • Namespaces►Newtonsoft.Json►JsonContainerAttribute►IsReference

    C#

    Json.NET-QuickStarts&APIDocumentationIsReferenceProperty

    Getsorsetsavaluethatindicateswhethertopreserveobjectreferencedata.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicboolIsReference{get;set;}

    PublicPropertyIsReferenceAsBoolean Get Set

    public:propertyboolIsReference{ boolget(); voidset(boolvalue);}

    Valuetruetokeepobjectreference;otherwise,false.Thedefaultisfalse.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50

  • Namespaces►Newtonsoft.Json►JsonContainerAttribute►TitleC#

    Json.NET-QuickStarts&APIDocumentationTitleProperty

    Getsorsetsthetitle.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstringTitle{get;set;}

    PublicPropertyTitleAsString Get Set

    public:propertyString^Title{ String^get(); voidset(String^value);}

    ValueThetitle.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • C#Namespaces►Newtonsoft.Json►JsonConvertJson.NET-QuickStarts&APIDocumentationJsonConvertClass

    ProvidesmethodsforconvertingbetweencommonlanguageruntimetypesandJSONtypes.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstaticclassJsonConvert

    PublicNotInheritableClassJsonConvert

    publicrefclassJsonConvertabstractsealed

    MembersAllMembers Methods Fields

    PublicProtected

    InstanceStatic

    Declared

    InheritedIcon Member Description

    DeserializeAnonymousType(String,T)

    DeserializestheJSONtothegivenanonymoustype.

    DeserializeObject(String) DeserializestheJSONtoa.NETobject.

    DeserializeObject(String,JsonSerializerSettings)

    DeserializestheJSONtoa.NETobject.

  • DeserializeObject(String,Type) DeserializestheJSONtothespecified.NETtype.

    DeserializeObject(String) DeserializestheJSONtothespecified.NETtype.

    DeserializeObject(String,JsonConverter[])

    DeserializestheJSONtothespecified.NETtype.

    DeserializeObject(String,JsonSerializerSettings)

    DeserializestheJSONtothespecified.NETtype.

    DeserializeObject(String,Type,JsonConverter[])

    DeserializestheJSONtothespecified.NETtype.

    DeserializeObject(String,Type,JsonSerializerSettings)

    DeserializestheJSONtothespecified.NETtype.

    DeserializeXmlNode(String) DeserializestheXmlNodefromaJSONstring.

    DeserializeXmlNode(String,String) DeserializestheXmlNodefromaJSONstringnestedinarootelment.

  • DeserializeXmlNode(String,String,Boolean)

    DeserializestheXmlNodefromaJSONstringnestedinarootelment.

    DeserializeXNode(String) DeserializestheXNodefromaJSONstring.

    DeserializeXNode(String,String) DeserializestheXNodefromaJSONstringnestedinarootelment.

    DeserializeXNode(String,String,Boolean)

    DeserializestheXNodefromaJSONstringnestedinarootelment.

    False RepresentsJavaScript'sbooleanvaluefalseasastring.Thisfieldisread-only.

    NaN RepresentsJavaScript'sNaNasastring.Thisfieldisread-only.

    NegativeInfinity RepresentsJavaScript'snegativeinfinityasastring.Thisfieldisread-only.

    http://msdn2.microsoft.com/en-us/library/bb493671http://msdn2.microsoft.com/en-us/library/bb493671http://msdn2.microsoft.com/en-us/library/bb493671

  • Null RepresentsJavaScript'snullasastring.Thisfieldisread-only.

    PopulateObject(String,Object) PopulatestheobjectwithvaluesfromtheJSONstring.

    PopulateObject(String,Object,JsonSerializerSettings)

    PopulatestheobjectwithvaluesfromtheJSONstring.

    PositiveInfinity RepresentsJavaScript'spositiveinfinityasastring.Thisfieldisread-only.

    SerializeObject(Object) SerializesthespecifiedobjecttoaJSONstring.

    SerializeObject(Object,Formatting) SerializesthespecifiedobjecttoaJSONstring.

    SerializeObject(Object,JsonConverter[])

    SerializesthespecifiedobjecttoaJSONstringusingacollectionofJsonConverter.

  • SerializeObject(Object,Formatting,JsonConverter[])

    SerializesthespecifiedobjecttoaJSONstringusingacollectionofJsonConverter.

    SerializeObject(Object,Formatting,JsonSerializerSettings)

    SerializesthespecifiedobjecttoaJSONstringusingacollectionofJsonConverter.

    SerializeXmlNode(XmlNode) SerializestheXMLnodetoaJSONstring.

    SerializeXmlNode(XmlNode,Formatting)

    SerializestheXMLnodetoaJSONstring.

    SerializeXmlNode(XmlNode,Formatting,Boolean)

    SerializestheXMLnodetoaJSONstring.

    SerializeXNode(XObject) SerializestheXNodetoaJSONstring.

    SerializeXNode(XObject,Formatting) SerializestheXNodetoaJSONstring.

    SerializeXNode(XObject,Formatting,Boolean)

    SerializestheXNodetoaJSONstring.

    http://msdn2.microsoft.com/en-us/library/bb493671http://msdn2.microsoft.com/en-us/library/bb493671http://msdn2.microsoft.com/en-us/library/bb493671

  • ToString(DateTime) ConvertstheDateTimetoitsJSONstringrepresentation.

    ToString(DateTimeOffset) ConvertstheDateTimeOffsettoitsJSONstringrepresentation.

    ToString(Boolean) ConvertstheBooleantoitsJSONstringrepresentation.

    ToString(Char) ConvertstheChartoitsJSONstringrepresentation.

    ToString(Enum) ConvertstheEnumtoitsJSONstringrepresentation.

    ToString(Int32) ConvertstheInt32toitsJSONstringrepresentation.

    ToString(Int16) ConvertstheInt16toitsJSONstringrepresentation.

    http://msdn2.microsoft.com/en-us/library/03ybds8yhttp://msdn2.microsoft.com/en-us/library/bb341783http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/k493b04shttp://msdn2.microsoft.com/en-us/library/1zt1ybx4http://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/e07e6fds

  • ToString(UInt16) ConvertstheUInt16toitsJSONstringrepresentation.

    ToString(UInt32) ConvertstheUInt32toitsJSONstringrepresentation.

    ToString(Int64) ConvertstheInt64toitsJSONstringrepresentation.

    ToString(UInt64) ConvertstheUInt64toitsJSONstringrepresentation.

    ToString(Single) ConvertstheSingletoitsJSONstringrepresentation.

    ToString(Double) ConvertstheDoubletoitsJSONstringrepresentation.

    ToString(Byte) ConvertstheBytetoitsJSONstringrepresentation.

    http://msdn2.microsoft.com/en-us/library/s6eyk10zhttp://msdn2.microsoft.com/en-us/library/ctys3981http://msdn2.microsoft.com/en-us/library/6yy583ekhttp://msdn2.microsoft.com/en-us/library/06cf7918http://msdn2.microsoft.com/en-us/library/3www918fhttp://msdn2.microsoft.com/en-us/library/643eft0thttp://msdn2.microsoft.com/en-us/library/yyb1w04y

  • ToString(SByte) ConvertstheSBytetoitsJSONstringrepresentation.

    ToString(Decimal) ConvertstheDecimaltoitsJSONstringrepresentation.

    ToString(Guid) ConvertstheGuidtoitsJSONstringrepresentation.

    ToString(String) ConvertstheStringtoitsJSONstringrepresentation.

    ToString(String,Char) ConvertstheStringtoitsJSONstringrepresentation.

    ToString(Object) ConvertstheObjecttoitsJSONstringrepresentation.

    True RepresentsJavaScript'sbooleanvaluetrueasastring.Thisfieldisread-only.

    http://msdn2.microsoft.com/en-us/library/f71b253dhttp://msdn2.microsoft.com/en-us/library/1k2e8atxhttp://msdn2.microsoft.com/en-us/library/cey1zx63http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/e5kfa45b

  • Undefined RepresentsJavaScript'sundefinedasastring.Thisfieldisread-only.

    InheritanceHierarchyObjectJsonConvert

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/e5kfa45b

  • Namespaces►Newtonsoft.Json►JsonConvert►DeserializeAnonymousType(String,T)

    C#

    Json.NET-QuickStarts&API

    DocumentationDeserializeAnonymousTypeMethod(value,anonymousTypeObject)

    DeserializestheJSONtothegivenanonymoustype.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstaticTDeserializeAnonymousType( stringvalue, TanonymousTypeObject)

    PublicSharedFunctionDeserializeAnonymousType(OfT)(_ valueAsString,_ anonymousTypeObjectAsT_)AsT

    public:genericstaticTDeserializeAnonymousType( String^value, TanonymousTypeObject)

    GenericTemplateParametersT

    Theanonymoustypetodeserializeto.Thiscan'tbespecifiedtraditionallyandmustbeinferedfromtheanonymoustypepassedasaparameter.

    Parameters

    http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • value(String)TheJSONtodeserialize.

    anonymousTypeObject(T)Theanonymoustypeobject.

    ReturnValueThedeserializedanonymoustypefromtheJSONstring.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • Namespaces►Newtonsoft.Json►JsonConvert►DeserializeObject()

    C#

    Json.NET-QuickStarts&APIDocumentationDeserializeObjectMethod

    MembersIcon Member Description

    DeserializeObject(String) DeserializestheJSONtoa.NETobject.

    DeserializeObject(String,JsonSerializerSettings)

    DeserializestheJSONtoa.NETobject.

    DeserializeObject(String,Type)

    DeserializestheJSONtothespecified.NETtype.

    DeserializeObject(String) DeserializestheJSONtothespecified.NETtype.

    DeserializeObject(String,JsonConverter[])

    DeserializestheJSONtothespecified.NETtype.

    DeserializeObject(String,JsonSerializerSettings)

    DeserializestheJSONtothespecified.NETtype.

    DeserializeObject(String,Type,JsonConverter[])

    DeserializestheJSONtothespecified.NETtype.

    DeserializeObject(String, DeserializestheJSONtothe

  • Type,JsonSerializerSettings)

    specified.NETtype.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonConvert►DeserializeObject(String)

    C#

    Json.NET-QuickStarts&APIDocumentationDeserializeObjectMethod(value)

    DeserializestheJSONtothespecified.NETtype.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstaticTDeserializeObject( stringvalue)

    PublicSharedFunctionDeserializeObject(OfT)(_ valueAsString_)AsT

    public:genericstaticTDeserializeObject( String^value)

    GenericTemplateParametersT

    Thetypeoftheobjecttodeserializeto.

    Parametersvalue(String)

    TheJSONtodeserialize.

    ReturnValueThedeserializedobjectfromtheJsonstring.

    http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonConvert►DeserializeObject(String)

    C#

    Json.NET-QuickStarts&APIDocumentationDeserializeObjectMethod(value)

    DeserializestheJSONtoa.NETobject.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstaticObjectDeserializeObject( stringvalue)

    PublicSharedFunctionDeserializeObject(_ valueAsString_)AsObject

    public:staticObject^DeserializeObject( String^value)

    Parametersvalue(String)

    TheJSONtodeserialize.

    ReturnValueThedeserializedobjectfromtheJsonstring.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

    http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • Namespaces►Newtonsoft.Json►JsonConvert►DeserializeObject(String,JsonConverter[])

    C#

    Json.NET-QuickStarts&APIDocumentationDeserializeObjectMethod(value,converters)

    DeserializestheJSONtothespecified.NETtype.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstaticTDeserializeObject( stringvalue, paramsJsonConverter[]converters)

    PublicSharedFunctionDeserializeObject(OfT)(_ valueAsString,_ ParamArrayconvertersAsJsonConverter()_)AsT

    public:genericstaticTDeserializeObject( String^value, ...array^converters)

    GenericTemplateParametersT

    Thetypeoftheobjecttodeserializeto.

    Parametersvalue(String)

    TheJSONtodeserialize.

    converters(JsonConverter[])

    http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • Converterstousewhiledeserializing.

    ReturnValueThedeserializedobjectfromtheJSONstring.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonConvert►DeserializeObject(String,JsonSerializerSettings)

    C#

    Json.NET-QuickStarts&APIDocumentationDeserializeObjectMethod(value,settings)

    DeserializestheJSONtothespecified.NETtype.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstaticTDeserializeObject( stringvalue, JsonSerializerSettingssettings)

    PublicSharedFunctionDeserializeObject(OfT)(_ valueAsString,_ settingsAsJsonSerializerSettings_)AsT

    public:genericstaticTDeserializeObject( String^value, JsonSerializerSettings^settings)

    GenericTemplateParametersT

    Thetypeoftheobjecttodeserializeto.

    Parametersvalue(String)

    Theobjecttodeserialize.

    settings(JsonSerializerSettings)

    http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • TheJsonSerializerSettingsusedtodeserializetheobject.Ifthisisnull,defaultserializationsettingswillbeisused.

    ReturnValueThedeserializedobjectfromtheJSONstring.

    Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonConvert►DeserializeObject(String,JsonSerializerSettings)

    C#

    Json.NET-QuickStarts&APIDocumentationDeserializeObjectMethod(value,settings)

    DeserializestheJSONtoa.NETobject.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstaticObjectDeserializeObject( stringvalue, JsonSerializerSettingssettings)

    PublicSharedFunctionDeserializeObject(_ valueAsString,_ settingsAsJsonSerializerSettings_)AsObject

    public:staticObject^DeserializeObject( String^value, JsonSerializerSettings^settings)

    Parametersvalue(String)

    TheJSONtodeserialize.

    settings(JsonSerializerSettings)TheJsonSerializerSettingsusedtodeserializetheobject.Ifthisisnull,defaultserializationsettingswillbeisused.

    ReturnValueThedeserializedobjectfromtheJSONstring.

    http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

  • Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonConvert►DeserializeObject(String,Type)

    C#

    Json.NET-QuickStarts&APIDocumentationDeserializeObjectMethod(value,type)

    DeserializestheJSONtothespecified.NETtype.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstaticObjectDeserializeObject( stringvalue, Typetype)

    PublicSharedFunctionDeserializeObject(_ valueAsString,_ typeAsType_)AsObject

    public:staticObject^DeserializeObject( String^value, Type^type)

    Parametersvalue(String)

    TheJSONtodeserialize.

    type(Type)TheTypeofobjectbeingdeserialized.

    ReturnValueThedeserializedobjectfromtheJsonstring.

    http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/42892f65http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/42892f65http://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/e5kfa45bhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/42892f65http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/42892f65http://msdn2.microsoft.com/en-us/library/42892f65

  • Assembly:Newtonsoft.Json(Module:Newtonsoft.Json)Version:4.0.2.0(4.0.2.13623)

  • Namespaces►Newtonsoft.Json►JsonConvert►DeserializeObject(String,Type,JsonConverter[])

    C#

    Json.NET-QuickStarts&APIDocumentationDeserializeObjectMethod(value,type,converters)

    DeserializestheJSONtothespecified.NETtype.

    DeclarationSyntaxC# VisualBasic VisualC++

    publicstaticObjectDeserializeObject( stringvalue, Typetype, paramsJsonConverter[]converters)

    PublicSharedFunctionDeserializeObject(_ valueAsString,_ typeAsType,_ ParamArrayconvertersAsJsonConverter()_)AsObject

    public:staticObject^DeserializeObject( String^valu


Recommended