Original: C#json serialization and deserialization
Windows Phone learning also for some time, want to do a news client practice practiced hand, so on the internet to see if there is no interface. In the Tengu podcast found Hot Hot Word News API Open Interface, interface provides JSON format data, because before the use of JSON, so on the online various search, technical discussion group of various questions ...
No more nonsense to say, the following to share my harvest. Look like me small white less detours.
An entity class
Public class Newsmodel { publicstringgetset;} Public string Get Set ; } Public string Get Set ; } }
Serialization methods
#regionJSON serialization of entity classes/// <summary> ///JSON serialization of entity classes/// </summary> /// <param name= "Item" >entity class object</param> /// <returns>JSON format string</returns> Public Static stringTojosndata (ObjectItem) {DataContractJsonSerializer Serializer=NewDataContractJsonSerializer (item. GetType ()); stringresult =string. Empty; using(MemoryStream ms =NewMemoryStream ()) {Serializer. WriteObject (MS, item); Ms. Position=0; using(StreamReader reader =NewStreamReader (MS)) {Result=Reader. ReadToEnd (); } } returnresult; } #endregion
JSON serialization of entity classes
List<newsmodel> Ltmodel =NewList<newsmodel>(); Ltmodel.add (NewNewsmodel {Title ="Title 1", Contents ="Content 1", times ="2014-12--2" }); Ltmodel.add (NewNewsmodel {Title ="Title 2", Contents ="Content 2", times ="2014-12--2" }); Ltmodel.add (NewNewsmodel {Title ="Title 3", Contents ="Content 3", times ="2014-12--2" }); Ltmodel.add (NewNewsmodel {Title ="Title 4", Contents ="Content 4", times ="2014-12--2" }); Ltmodel.add (NewNewsmodel {Title ="Title 5", Contents ="Content 5", times ="2014-12--2" }); Ltmodel.add (NewNewsmodel {Title ="Title 6", Contents ="Content 6", times ="2014-12--2" }); stringJsonstr=jsonhelper.tojosndata (Ltmodel);
The output JSON string is:
The way to sequence a Json string as a solid object is to use Newtonsoft.Json.dll, which can be downloaded on the website http://json.codeplex.com/
After introducing namespaces, it's easy.
New List<newsmodel>(); var root = jsonconvert.deserializeobject<newsmodel[]>(jsonstr); foreach (var in root) { Demodel.add (new newsmodel {Title = Item). Title, Contents = Item. Contents, times = item. Times});
This deserializes the JSON string into a list collection.
Reference: Http://stackoverflow.com/questions/8639421/json-parsing-in-windows-phone-7.
Serialization and deserialization of C#json