ThefollowingtopicwillintroduceawaytoworkwithJsonusingC#languageandconceptsofSerializationand Deserialization.
{
“id”:89,
“name”:”AldousHuxley”,
“type”:”Author”,
“books”:[{
“name”:”BraveNewWorld”,
“date”:1932
},
{
“name”:”EyelessinGaza”,
“date”:1936
},
{
“name”:”TheGeniusandtheGoddess”,
“date”:1955
}]
}
IfyouarenewintoJson,hereisanexemplifiedtutorial.
Section82.2:FirstthingsFirst:LibrarytoworkwithJson
ToworkwithJsonusingC#,itisneedtouseNewtonsoft(.netlibrary).Thislibraryprovidesmethodsthatallowsthe programmerserializeanddeserializeobjectsandmore.Thereisatutorialifyouwanttoknowdetailsaboutits methods and usages.
If you use Visual Studio, go to Tools/Nuget Package Manager/Manage Package to Solution/ and type “Newtonsoft” into thesearchbarandinstallthepackage.Ifyoudon’thaveNuGet,thisdetailedtutorialmighthelpyou.
Before reading some code, it is important to undersand the main concepts that will help to program applications using json.
Serialization:Processofconvertingaobjectintoastreamofbytesthatcanbesentthroughapplications. The following code can be serialized and converted into the previous json.
Deserialization:Processofconvertingajson/streamofbytesintoanobject.Itsexactlytheopposite process of serialization. The previous json can be deserialized into an C# object as demonstrated in examples below.
To work this out, it is important to turn the json structure into classes in order to use processes already described.If you use Visual Studio, you can turn a json into a class automatically just by selecting “Edit/Paste Special/Paste JSON as Classes”and pasting the json structure.
usingNewtonsoft.Json;
classAuthor
{
[JsonProperty(“id”)]//Setthevariablebelowtorepresentthejsonattribute
publicintid;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â //”id”
[JsonProperty(“name”)]
public string name;
[JsonProperty(“type”)]
publicstringtype;
[JsonProperty(“books”)]
public Book[] books;
publicAuthor(intid,stringname,stringtype,Book[]books){ this.id= id;
this.name=name;
this.type=type;
this.books = books;
}
}
classBook
{
[JsonProperty(“name”)]
publicstringname;
[JsonProperty(“date”)]
publicDateTimedate;
}
staticvoidMain(string[]args)
{
Book[]books=newBook[3];
Authorauthor=newAuthor(89,”AldousHuxley”,”Author”,books); stringobjectDeserialized=JsonConvert.SerializeObject(author);
//Convertingauthorintojson
}
Themethod”.SerializeObject”receivesasparameteratypeobject,soyoucanputanythingintoit.
Youcanreceiveajsonfromanywhere,afileorevenaserversoitisnotincludedinthefollowingcode.
staticvoidMain(string[]args)
{
stringjsonExample;//Hasthepreviousjson
Authorauthor=JsonConvert.DeserializeObject<Author>(jsonExample);
}
Themethod”.DeserializeObject”deserializes’jsonExample‘intoan”Author“object.Thisiswhyitisimportanttoset the json variables in the classes definition, so the method access it in order to fill it.
Section 82.6: Serialization & De-Serialization Common Utilities function
Thissampleusedtocommonfunctionforalltypeobjectserializationanddeserialization.
usingSystem.Runtime.Serialization.Formatters.Binary;
usingSystem.Xml.Serialization;
namespaceFramework
{
publicstaticclassIGUtilities
{
publicstaticstringSerialization(thisTobj)
{
stringdata=JsonConvert.SerializeObject(obj);
returndata;
}
publicstaticTDeserialization(thisstringJsonData)
{
Tcopy=JsonConvert.DeserializeObject(JsonData); returncopy;
}
publicstaticTClone(thisTobj)
{
stringdata=JsonConvert.SerializeObject(obj);Tcopy=Json
Convert.DeserializeObject(data); returncopy;
}
}
}
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024