[. NET Deep breath] how to deserialize dynamic JSON and serialize json

Source: Internet
Author: User

[. NET Deep breath] how to deserialize dynamic JSON and serialize json

 

In addition to SOAP, XML, binary, and other serialization and deserialization,. net also supports JSON serialization. However, in actual development, JSON objects with undefined structures may be dynamically generated by other code. You cannot estimate the structure of these objects in advance, even its field names are dynamically changed.

In this case, it is difficult to use a fixed class for deserialization. Later, I tried to derive a custom dynamic type from the DynamicObject class, I hope this method can be used to read the dynamically generated JSON, but the result is still unavailable. Later, I implemented the ISerializable interface and tried to control the Data Reading by myself, but it still failed.

In the end, I concluded that only the following method is easier, and dynamic JSON can be deserialized.

A friend who develops ASP. NET should be familiar with the JavaScriptSerializer class located in the namespace of System. Web. Script. Serialization. Because this class is used for Web development, it can be used in the entire. net Framework, that is, you can still use it in WinForm, WPF, and other programs. This class is used to serialize and deserialize the specified JSON string. the type involved in the operation can be fixed. If the JSON is of a fixed structure, this is feasible. For JSON with an unfixed structure, this class can be operated in the form of a dictionary,That is, after the DeserializeObject method is called, an Object of the object type will be returned. In fact, this Object implements the IDictionary <string, object> interface.In this way, the deserialization result can be operated as a dictionary. If a nested object exists in JSON, the returned dictionary object is nested with the dictionary object.

 

So I wrote the following class:

Public sealed class JsonObjectReader {private string innerJson = null; public JsonObjectReader (string json) {innerJson = json;} public dynamic GetObject () {dynamic d = new ExpandoObject (); // deserialize the JSON string JavaScriptSerializer s = new JavaScriptSerializer (); object resobj = s. deserializeObject (this. innerJson); // copy data IDictionary <string, object> dic = (IDictionary <string, object>) resobj; IDictionary <string, object> dicdyn = (IDictionary <string, object>) d; foreach (var item in dic) {dicdyn. add (item. key, item. value) ;}return d ;}}


Someone will ask me why the GetObject method returns a dynamic type? ExpandoObject is an easy-to-use and ready-made dynamic type. When declaring a variable in C #, the dynamic keyword is applied, telling the compiler that this guy is a dynamic type, during the compilation check, you can "open the network ". In addition, I found that the ExpandoObject class explicitly implements the IDictionary <string, object> interface, which means you can forcibly convert it into Dictionary data for operation.

This method can be used as a dynamic object if it is easy to use. It can also be used as Dictionary data when it is not convenient to use.

 

The following is an example of inaccessibility to dynamic access:

String json = "{" + "\" 0592 \ ": \" Xiamen City \ "," + "\" 0351 \ ": \" Taiyuan City \", "+" \ "0411 \": \ "Dalian City \", "+" \ "0459 \": \ "Daqing City \" "+ "}"; jsonObjectReader rd = new JsonObjectReader (json); dynamic res = rd. getObject (); IDictionary <string, object> d = (IDictionary <string, object>) res; foreach (var item in d) {Console. writeLine ($ "{item. key} = {item. value }");}

You will find that this JSON file is difficult to deserialize using conventional methods, because its field is the district code of the city, which is not fixed, when declaring a class, you cannot determine the class attributes or field members in advance. At the same time, you also find that the field name is a number. Even if you get the result with a dynamic object, you cannot access it with a syntax like obj.0459, because the identifier cannot start with a number. In this case, dynamic objects cannot be used for access, but it can be converted to dictionary objects for processing.

The result is shown in.

 

 

However, in the following usage, because the JSON field name does not start with a number, it can be accessed as a dynamic object.

Json = "{\" Name \ ": \" James \ ", \" Age \ ": 25, \" Email \ ": \" abcd@dog.cc \"}"; jsonObjectReader rd2 = new JsonObjectReader (json); dynamic res2 = rd2.GetObject (); Console. writeLine ($ "Name: {res2.Name}"); Console. writeLine ($ "Age: {res2.Age}"); Console. writeLine ($ "Email: {res2.Email }");

Because the Name, Age, and Email fields do not start with a number and are required by the symbol identifier, you can use res2.Name to access them later, just like accessing a common object instance.

The result is as follows.

 

It should be noted that this method is only used for. NET Framework applications, such as ASP. NET and WPF. If it is a Windows Store App, you can use JSON-related classes in the rt api for processing. These classes are located in the Windows. Data. Json namespace..

 

Download Sample Code

 

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.