Reprint C # object to JSON serialization

Source: Internet
Author: User

Reprint Original Address: http://www.cnblogs.com/plokmju/p/ObjectByJson.html

Json

Json (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of JS. JSON takes a completely language-independent text format. This makes JSON an ideal data exchange language. Easy to read and write, but also easy to machine parse and generate.

JSON is simply the object and array in JS, so JSON also has two structures: objects, arrays.

    • JSON object: JSON object definition in curly braces "{}", in the form of Key:value key-value pairs to hold data, multiple data using semicolons ";" Split

    • JSON arrays: JSON arrays are defined in square brackets "[]", storing data as strings, multiple data using semicolons ";" Split

JSON serialization and deserialization

For. NET, the DataContractJsonSerializer class has been provided since 3.5 and requires reference to dll,system.runtime.serialization. The way to use it is simple, you need to know the type of object to be converted, and then convert it by MemoryStream Stream writes. For DataContractJsonSerializer objects, serialization and deserialization only need to know two methods, both of which have multi-put overloads for different environments, two methods:

    • WriteObject: Serializes the specified object into JSON data and writes the resulting JSON to the stream.
    • ReadObject: reads the document stream in JSON format and returns the deserialized object.

Using DataContractJsonSerializer to serialize objects and deserialize the JSON is simpler, as shown in the following example code:

   Private Static stringgetjsonbyobject (Object obj)2         { 3             //instantiating an DataContractJsonSerializer object, requiring the type of object to be serialized 4DataContractJsonSerializer serializer =NewDataContractJsonSerializer (obj. GetType ()); 5             //instantiate a memory stream for storing serialized data 6MemoryStream stream =NewMemoryStream ();7             //serializing an object using WriteObject 8Serializer. WriteObject (stream, obj); 9             //write in memory streamTen             byte[] Databytes =New byte[Stream. Length]; OneStream. Position =0; AStream. Read (Databytes,0, (int) stream. Length); -             //Convert to string by UTF8 format -             returnEncoding.UTF8.GetString (databytes); the         } -  -         Private StaticObject Getobjectbyjson (stringjsonstring, Object obj) -         { +             //instantiating an DataContractJsonSerializer object, requiring the type of object to be serialized -DataContractJsonSerializer serializer =NewDataContractJsonSerializer (obj. GetType ()); +             //save JSON into the memory stream AMemoryStream stream =NewMemoryStream (Encoding.UTF8.GetBytes (jsonstring)); at             //Deserializing into an object using the ReadObject method -             returnSerializer. ReadObject (stream); -}

With this transformation class, objects can be serialized into JSON and deserialized into objects. But there is a problem, that is, for the collection type of data, can be serialized into JSON, but this JSON deserialization will fail, I have not found here a better way to deserialize the collection type of data. Now there are some common. NET type of data for serialization presentation.

Creates a new class jsonobject that gets the data, returning a person (id,name,age) object, List<person> object, List<string> object, respectively,list< Dictionary<string, object>> objects, respectively, look at the serialized data.

Jsonobject class:

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingsystem.web;5  6 namespaceWebdemo.json7 { 8     Static  Public classJsonobject9     {Ten         Static  PublicPerson Getperson () One         { APerson person =NewPerson (); -Person.id = -; -Person.name ="slive"; thePerson.age = -; -             returnPerson ; -         } -         Static  PublicList<person>getpersonlist () +         { -List<person> personlist =NewList<person>(); +Person person =NewPerson (); APerson.id = -; atPerson.name ="slive"; -Person.age = -; -Person Person2 =NewPerson (); -Person2.id = -; -Person2.name ="Jack"; -Person2.age = the; inPerson Person3 =NewPerson (); -Person3.id = +; toPerson3.name ="Damon"; +Person3.age = Wu; -Personlist.add (person); thePersonlist.add (person2); *Personlist.add (Person3); $             returnpersonlist;Panax Notoginseng         } -         Static  Publiclist<string>getstringlist () the         { +list<string> stringlist =Newlist<string>(); AStringlist. ADD ("Jack"); theStringlist. ADD ("Dick"); +Stringlist. ADD ("Sean"); -             returnstringlist; $         } $         Static  Publiclist<dictionary<string,Object>>getdiclist () -         { -list<dictionary<string,Object>> diclist =Newlist<dictionary<string,Object>>(); thedictionary<string,Object> Dic1 =Newdictionary<string,Object>(); -Dic1. ADD ("ID", -);WuyiDic1. ADD ("name","Jerry"); theDic1. ADD (" Age", -); -dictionary<string,Object> Dic2 =Newdictionary<string,Object>(); WuDic2. ADD ("ID", -); -Dic2. ADD ("name","Meimei"); AboutDic2. ADD (" Age", at); $dictionary<string,Object> dic3 =Newdictionary<string,Object>(); -Dic3. ADD ("ID", +); -Dic3. ADD ("name","Damon"); -Dic3. ADD (" Age", -); ADiclist.add (DIC1); +Diclist.add (DIC2); theDiclist.add (DIC3); -             returndiclist; $         } the     } theCopy the Code

The data returned by the Jsonobject is serialized separately, and the result can be seen:

    • Getperson (): {"Age": "id": +, "name": "Slive"}
    • Getpersonlist (): [{"Age": "id": +, "name": "Slive"},{"Age": "id": +, "name": "Jack"},{"age": Si, "id": +, "name": " Damon "}]
    • Getstringlist (): ["Jack", "Dick", "Sean"]
    • Getdiclist (): [[{"Key": "id", "value": 17},{"key": "Name", "Value": "Jerry"},{"key": "Age", "value": 24}],[{"key": "id", " Value ": 18},{" key ":" Name "," Value ":" Meimei "},{" key ":" Age "," value ": 23}],[{" key ":" id "," value ": 19},{" key ":" Name "," Value ":" Damon "},{" Key ":" Age "," value ": 28}]

Reprint C # object to JSON serialization

Related Article

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.