【. NET deep breathing "how to deserialize dynamic JSON

Source: Internet
Author: User

In addition to supporting serialization and deserialization of soap, XML, binary, and so on, the. NET itself later added support for serialization of JSON. However, in real-world development, you will often encounter structure-indeterminate JSON objects, which may be generated dynamically by other code, and you cannot estimate its structure beforehand, even if its field names are changed dynamically.

In this case, it is difficult to deserialize with a fixed class, and later I try to derive a custom dynamic type from the DynamicObject class, which I hope will be able to read the dynamically generated JSON, but the result is still not And then I realized the ISerializable interface, thinking about the control of the data read, but still did not.

Finally, I conclude that only the following method is more convenient and can be used to deserialize the dynamic JSON.

A friend who does ASP. NET development should be familiar with a class-the JavaScriptSerializer class that is located under the System.Web.Script.Serialization namespace. Because this class is for web development services, it can actually be used throughout the. NET Framework, i.e. you can still use it in WinForm, WPF, and other programs. The function of this class is to serialize and deserialize the specified JSON string, and the type of the participating operation can be fixed, if the JSON is a fixed structure, it is possible. In the case of JSON with unstructured structure, this class can be manipulated in the form of a dictionary, that is, when the Deserializeobject method is called, it returns an object of the object type, which actually implements the idictionary<string. Object> interface , so that the results of deserialization can be manipulated as a dictionary. If there are nested objects inside the JSON, the Dictionary object is nested within the returned Dictionary object.

So, I wrote a class like this:

     Public Sealed classJsonobjectreader {Private stringInnerjson =NULL;  PublicJsonobjectreader (stringJSON) {Innerjson=JSON; }         Public DynamicGetObject () {DynamicD =NewExpandoObject (); //deserializing a JSON stringJavaScriptSerializer s =NewJavaScriptSerializer (); ObjectResobj = S.deserializeobject ( This. Innerjson); //Copy Dataidictionary<string,Object> dic = (idictionary<string,Object>) Resobj; IDictionary<string,Object> Dicdyn = (idictionary<string,Object>) D; foreach(varIteminchdic) {Dicdyn. ADD (item. Key, item.            Value); }            returnD; }    }


Someone will ask me, GetObject. How do I return to a dynamic type? For ease of operation, ExpandoObject is an easy-to-use, readily available dynamic type that applies the dynamic keyword when declaring a variable in C #, telling the compiler that this guy is a dynamically typed, and can be "spared" when compiling the check. Moreover, I found that the ExpandoObject class is explicitly implemented Idictionary<string, object> interface, you can also cast it to the dictionary data to operate.

This practice double benefit, if convenient to use, as a dynamic object to access, when inconvenient to use, can also be used as a dictionary data.

Here is an example of an inconvenient use of dynamic access:

            stringJSON ="{"+"\ "0592\": \ "Xiamen city \","+"\ "0351\": \ "Taiyuan City \","+"\ "0411\": \ "Dalian \","+"\ "0459\": \ "Daqing \""+"}"; Jsonobjectreader Rd=NewJsonobjectreader (JSON); Dynamicres =Rd.            GetObject (); IDictionary<string,Object> d = (idictionary<string,Object>) Res; foreach(varIteminchd) {Console.WriteLine ($"{item. Key} = {item. Value}"); }

You will find that this JSON is difficult to deserialize in the usual way, because its field is the city's area code and is not fixed, and you cannot determine the class's properties or field members in advance when declaring the class. You also find that field names are numbers, and even if you get results from a dynamic object, you cannot access them in the same syntax as obj.0459, because identifiers cannot start with numbers. In this case, it cannot be accessed with a dynamic object, but it can be converted to a Dictionary object for processing.

Get results like.

However, the following usage is possible because the field name of the JSON is not the beginning of the number, so it can be accessed as a dynamic object.

JSON ="{\ "name\": \ "Xiao Ming \", \ "age\": "email\": \ "[Email protected]\"}"; Jsonobjectreader Rd2=NewJsonobjectreader (JSON); DynamicRes2 =Rd2.            GetObject (); Console.WriteLine ($"name: {res2. Name}"); Console.WriteLine ($"Age: {res2. AGE}"); Console.WriteLine ($"E -mail: {res2. Email}");

Because name, age, E-mail These fields are not the beginning of the numbers, the specification of the symbol identifiers is required, so you can use res2 later. Name in the same way as accessing a normal object instance.

The results are as follows.

Finally, to illustrate, this method is only used for. NET framework applications, such as ASP. In the case of Windows Store apps, you can use JSON-related classes in the RT API that are located in the Windows.Data.Json namespace .

Sample code Download

【. NET deep breathing "how to deserialize dynamic JSON

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.