Use Json. NET to serialize the required data, json.net serialization

Source: Internet
Author: User
Tags net serialization

Use Json. NET to serialize the required data, json.net serialization

During development, we often need to deal with the Json data format. For example, in Web development, data is often transmitted to the page through Json and then processed. When using Json, we often involve the use of several serialized objects:DataContractJsonSerializer,JavaScriptSerializerAndJson. NET. Most people will choose Json with better performance and versatility. NET, this is not a Microsoft class library, but an Open Source world-class Json operation class library, from the performance comparison below we can see one of its performance advantages.

Json. NET can be well serialized or deserialized. NET, and its other advantage is that you can configure the Attribute to specify the name of the output Attribute or whether to output the Attribute.

JSON (JavaScript Object Notation, JavaScript Object Notation) is a lightweight data exchange format. JSON is a set of "name-value pairs. The structure consists of braces '{}', braces '[]', comma ',', colons ':', and double quotation marks '. The data types include Object, Number, boolean, String, Array, and NULL.

1. Use Json data on the Web

In my MVC + EasyUI-based Web development framework, the Web interface layer uses Ajax to obtain the required data, and then binds it to the tree list control or other interface controls, in the previous Web framework series, I have introduced many operations in Json format.

1) Web Development Framework experience based on MVC4 + EasyUI (3)-build menu data using Json object classes

2) Web Development Framework experience based on MVC4 + EasyUI (2)-build a Web interface using the EasyUI tree control

In the MVC view, the code for initializing the tree control after Json data is requested by the Web is as follows:

// Initialize the organization list function initDeptTreeview () {$ ("# loading "). show (); $ ('# treeDept '). tree ({url: '/User/GetMyDeptTreeJson? UserId = @ Session ["UserId"] ', onClick: function (node) {loadDataByOu (node. id) ;}}); $ ("# loading "). fadeOut (500 );}

Or User Role initialization interface code

                $('#lbxRoles').empty();                $.getJSON("/Role/GetRolesByUser?r=" + Math.random() + "&userid=" + info.ID, function (json) {                    $.each(json, function (i, item) {                        $('#lbxRoles').append('<option value="' + item.ID + '">' + item.Name + '</option>');                    });                });

 

As mentioned above, Json. NET has the property configuration function, which can specify whether an attribute is output or whether the output name is escaped. By default, the field names in the serialized Json. Net results are the same as the attribute names in the class. to customize the serialized field names, you can use JsonProperty.

We know that in the Tree control of EasyUI, its data format, except that one id and text are required, many of its attributes are optional, that is, in Json, you can not output the content of an attribute. This configuration

[JsonProperty( NullValueHandling = NullValueHandling.Ignore)]

You can ignore the output of an attribute if its value is null.

The data in the tree control also has a checked attribute. If there is no escape function, we need to specify the attribute as checked, and checked is the reserved keyword in C #, which cannot be used. Json. NET provides the Configuration Attribute of the escape Function to solve the problem well, as shown below.

        [JsonProperty(PropertyName = "checked", NullValueHandling = NullValueHandling.Ignore)]        public bool? Checked { get; set; }

Therefore, the Tree data object information of EasyUI can be defined as follows in C # (the definition of DataContract and DataMember can be ignored here ).

/// <Summary> /// defines the relevant data of the EasyUI tree, convenience for the Controller to generate Json data for transmission // </summary> [DataContract] [Serializable] public class EasyTreeData {// <summary> /// ID /// </summary> [DataMember] public string id {get; set ;}//< summary> /// node name /// </summary> [DataMember] public string text {get; set ;} /// <summary> /// whether to expand /// </summary> [JsonProperty (NullValueHandling = NullValueHandling. ignore)] [DataMember] public string state {get; set ;}/// <summary> // icon style /// </summary> [DataMember]
[JsonProperty (NullValueHandling = NullValueHandling. Ignore)]
Public string iconCls {get; set ;}
[JsonProperty (PropertyName = "checked", NullValueHandling = NullValueHandling. Ignore)] [DataMember (Name = "checked")] public bool? Checked {get; set ;}/// <summary> // subnode set /// </summary> [DataMember] public List <EasyTreeData> children {get; set ;}

Use the object class on and use Json. NET to serialize our data. We may get the following Json data.

[{Id: "-1", text: "NONE", state: "open ",
Checked: true, children: []}, {id: "6", text: "General Manager", state: "open", iconCls: "icon-group", children: []}]

From the preceding Json data, we can see that the Checked attribute is successfully converted to the name attribute of the checked, marked as [JsonProperty (NullValueHandling = NullValueHandling. ignore)], and the property with a null value will not appear in the Json string.

In some cases, this is exactly what we need.

2. Use Json in interface development

API interfaces use a large amount of Json data. Not only does a lot of returned data use Json expressions, but most of the Post data also uses the Json data format, for example, in my first two articles C # development portal and application (5) -- User Group Information Management, C # development portal and application (4) -- Focus on the user list and detailed information management"

Many interfaces use Json data.

If the Json data of the List of consumers is returned, it is shown as follows.

{"total":2,"count":2,"data":{"openid":["","OPENID1","OPENID2"]},"next_openid":"NEXT_OPENID"}

Create a user group. The returned data format is as follows, which is also Json data.

{    "group": {        "id": 107,         "name": "test"    }}

Through the following Json. NET-based Json data conversion, You can smoothly convert the Json string to the corresponding object.

/// <Summary> /// Json string operation helper class /// </summary> public class JsonHelper <T> where T: class, new () {/// <summary> /// check the returned record. If no error is returned, or the result indicates success, no exception is thrown. // </summary> /// <param name = "content"> returned result </param> /// <returns> </returns> private static bool VerifyErrorCode (string content) {if (content. contains ("errcode") {ErrorJsonResult errorResult = JsonConvert. deserializeObject <ErrorJsonResult> (content ); // An exception is recorded only when an operation is unsuccessful, because some operations return normal results ({"errcode": 0, "errmsg": "OK"}) if (errorResult! = Null & errorResult. errcode! = ReturnCode. Successful request) {string error = string. Format ("request error! Error code: {0}, Description: {1} ", (int) errorResult. errcode, errorResult. errmsg); LogTextHelper. error (errorResult); throw new WeixinException (error); // throw an Error} return true ;} /// <summary> /// convert the Json string to a specific object // </summary> /// <param name = "url"> return the url of the Json data </param> // <returns> </returns> public static T ConvertJson (string url) {HttpHelper helper = new HttpHelper (); string content = helper. getHtml (url); VerifyErrorCode (content); T result = JsonConvert. deserializeObject <T> (content); return result ;}}

If you want to convert an object to a Json string, the Code is also very simple.

JsonConvert.SerializeObject(obj, Formatting.Indented);

 

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.