Using Newtonsoft.Json.dll (json.net) to dynamically parse JSON,. NET JSON serialization and deserialization (i)

Source: Internet
Author: User

In development, I love the convenience of dynamic languages and anonymous objects, JSON. NET has the ability to serialize and deserialize arbitrary JSON content dynamically, without having to map it to specific strongly typed objects, which can handle indeterminate types (collections, dictionaries, dynamic objects, and anonymous objects), in which I will pass Jtoken, Jobject and Jarray to dynamically parse JSON objects, making it easy to create and retrieve JSON content without the underlying type. Creating JSON objects with Jobject and Jarray we first use a very simple method to dynamically create some JSON, which can be done by Jtoken derived json.net objects, the most common Jtoken-derived classes are jobject and Jarray.
Because Jtoken implements the Idynamicmetaprovider dynamic language interface, you can use the Dynamic keyword to visually create a dynamic object and serialize the dynamic object into a JSON string.


Address of Newtonsoft.json:

Official website: http://json.codeplex.com/

Source Address: Https://github.com/JamesNK/Newtonsoft.Json

Newtonsoft.Json.dll Download: https://github.com/JamesNK/Newtonsoft.Json/releases

Example 1,
Create an example of a music album structure with Jarray and Jobject:

            //Newtonsoft.Json.Linq.JObject jsonobject = new Newtonsoft.Json.Linq.JObject {{"entered", DateTime.Now}};Newtonsoft.Json.Linq.JObject Jsonobject=NewNewtonsoft.Json.Linq.JObject (); Jsonobject.add ("entered", DateTime.Now); DynamicAlbum =Jsonobject; Album. Albumname="Dirty Deeds Done Dirt Cheap"; Album. Artist="Ac/dc/dvd"; Album. Yearreleased=DateTime.Now.Year; Album. Songs=NewNewtonsoft.Json.Linq.JArray () as Dynamic; DynamicSong =NewNewtonsoft.Json.Linq.JObject (); Song. Songname="Dirty Deeds Done Dirt Cheap"; Song. Songlength="4:05"; Album.            Songs.add (song); Song=NewNewtonsoft.Json.Linq.JObject (); Song. Songname="Love at first feel"; Song. Songlength="3:01"; Album.            Songs.add (song); Song=NewNewtonsoft.Json.Linq.JObject (); Song. Songname="Little Apple"; Song. Songlength="03:32"; Album.            Songs.add (song); Console.WriteLine (album.            ToString ()); Console.ReadLine ();


The most important thing about the above code is that the dynamic object can be JSON serialized without explicitly specifying the type, whereas the Jobject object simply receives the data, and the structure is generated at run time by the dynamic language, which means that the code can be compiled at run time, thus embodying the advantages of dynamic language. The result of serialization is as follows:

Example 2,

            //Newtonsoft.Json.Linq.JObject jsonobject = new Newtonsoft.Json.Linq.JObject {{"entered", DateTime.Now}};Newtonsoft.Json.Linq.JObject Jsonobject =NewNewtonsoft.Json.Linq.JObject (); Jsonobject.add ("entered", DateTime.Now); DynamicAlbum =Jsonobject; Album. Albumname="non-mainstream songs"; foreach(varIteminchJsonobject)//The cyclic output dynamic value Jobject (base class Jcontainer, Jobject, and Jarray) is a collection that implements the IEnumerable interface, so you can also easily iterate through the runtime{Console.WriteLine (item. Key+"The values are:"+item.            Value.tostring ()); }

The result of the execution is:

Example 3:

The Jobject.parse () and Jarray.parse () methods import the JSON format, and the Jtoken structure supports the Parse () and load () methods, which can read JSON data from a string or various streams, respectively. Jvalue includes the most core JSON parsing capabilities, supporting the conversion of strings to dynamic objects that we are familiar with. Converts a JSON string into a Jobject object and casts it to a dynamic type.

            varJsonstring =@""; DynamicJSON = Newtonsoft.Json.Linq.JToken.Parse (jsonstring) as Dynamic; stringName =JSON.            Name; stringCompany =Json.company; DateTime entered=JSON.            entered; Console.WriteLine ("Name:"+name); Console.WriteLine ("Company :"+Company ); Console.WriteLine ("entered:"+ entered);

Execution Result:

Example 4:

Maps Jobject and Jarray instances to a strongly typed object, so you can mix dynamic and static types in the same piece of code

            stringJsonString1 =@""; Newtonsoft.Json.Linq.JArray UserAarray1= Newtonsoft.Json.Linq.JArray.Parse (jsonString1) asNewtonsoft.Json.Linq.JArray; List<User> Userlistmodel = useraarray1.toobject<list<user>>(); foreach(varUserModel1inchUserlistmodel) {Console.WriteLine ("Name:"+usermodel1.name); Console.WriteLine ("Age :"+usermodel1.age); } Console.WriteLine (""); stringJsonstring =@"[{"" Name "": "" Small apple "," "Age" ": " ""}]"; Newtonsoft.Json.Linq.JArray Useraarray= Newtonsoft.Json.Linq.JArray.Parse (jsonstring) asNewtonsoft.Json.Linq.JArray; Newtonsoft.Json.Linq.JObject Jobject= useraarray[0] asNewtonsoft.Json.Linq.JObject; User Usermodel= jobject.toobject<user>(); Console.WriteLine ("Name:"+usermodel.name); Console.WriteLine ("Age :"+ usermodel.age);
     Public class User    {        publicstringsetget;}          Public int Set Get ; }    }

Execution Result:

Example 5,

Json. NET support for dynamic languages, but also do not forget its strong support for static types, about how to serialize and deserialize strongly typed objects, JsonConvert is a high-level static class that wraps lower levels of functionality, but you can also use the Jsonserializer class, The class can serialize and deserialize various streams

Usertype album =Newusertype () {Type="Normal User", Userlistmodel=NewList<user>()                 {                    NewUser () {Name="Zhang San", Age= -                    },                    NewUser () {Name="John Doe", Age= -                    }                }            }; //Serialize to String            stringJson2 =Newtonsoft.Json.JsonConvert.SerializeObject (album, Newtonsoft.Json.Formatting.Indented); Console.WriteLine ("Serialization Results"); Console.WriteLine ("");            Console.WriteLine (Json2); Usertype usertype= newtonsoft.json.jsonconvert.deserializeobject<usertype>(Json2); Console.WriteLine (""); Console.WriteLine ("deserialization:"); Console.WriteLine ("Type:"+Usertype.type); Console.WriteLine (""); foreach(varUsermodelinchUsertype.userlistmodel) {Console.WriteLine ("Name:"+usermodel.name); Console.WriteLine ("Age :"+usermodel.age); }
     Public classusertype { Public stringType {Get;Set; }  PublicList<user> Userlistmodel {Get;Set; } }     Public classUser { Public stringName {Set;Get; }  Public intAge {Set;Get; } }

Execution Result:

Using Newtonsoft.Json.dll (json.net) to dynamically parse JSON,. NET JSON serialization and deserialization (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.