Newtonsoft.json Advanced Usage

Source: Internet
Author: User
Tags net serialization

Original: Newtonsoft.json Advanced usage

Mobile applications pay attention to speed, good experience. Just a project on hand. The server-side interface has performance issues that need to be optimized. In multiple modifications to the interface, the entity adds many fields for intermediate calculations or storage, And then finally serialized return data with Newtonsoft.json, after analyzing a simple list interface each row of data returned 16 fields, but the mobile app side only used 7 of the fields, the remaining 9 fields of data are all redundant, if the interface return data is 40K size, that is, about 20K of data is Invalid data, 20K download under 3G network almost need 1s, do not return invalid data at least can save 1s time, greatly improve the user experience. This article will introduce some of the advanced usage of Newtonsoft.json, which can be modified with very little code to solve the above problems.

Read Catalogue

    • Newtonsoft.json Introduction
    • Basic usage
    • Advanced usage
    • Summarize
Back to top Newtonsoft.json introduction

When doing development, many data exchanges are transmitted in JSON format. When using Json, we often involve the use of several serialized objects:datacontractjsonserializer,javascriptserializer , and json.net that is Newtonsoft.json. Most people will choose performance and versatility good json.net, this is not Microsoft's class library, but an open source world-class JSON Operation class Library, from the following performance comparison can see one of its performance advantages.

Complete API introduction, easy to use

Go back to the top of basic usage

Json.NET is a support for serializing and deserializing the datatable,dataset,entity framework and Entity. The following are examples of serialization and deserialization, respectively.

DataTable:

            //Serializing a DataTableDataTable dt =NewDataTable (); Dt. Columns.Add (" Age", Type.GetType ("System.Int32")); Dt. Columns.Add ("Name", Type.GetType ("System.String")); Dt. Columns.Add ("Sex", Type.GetType ("System.String")); Dt. Columns.Add ("Ismarry", Type.GetType ("System.Boolean"));  for(inti =0; I <4; i++) {DataRow Dr=dt.                NewRow (); dr[" Age"] = i +1; dr["Name"] ="Name"+i; dr["Sex"] = i%2==0?"male":"female"; dr["Ismarry"] = i%2>0?true:false; Dt.            Rows.Add (DR); } Console.WriteLine (Jsonconvert.serializeobject (DT));

Use the string above to deserialize

string json = jsonconvert.serializeobject (dt); DT=jsonconvert.deserializeobject<datatable>  foreach in dt. Rows) {Console.WriteLine ("{0}\t{1}\t{2}\t{3}\t", dr[0], dr[1] , dr[2], dr[3]); }

Entity serialization, like a DataTable, does not introduce too much.

Back to top advanced usage

1. Ignore certain properties

2. Handling of default values

3. Handling of NULL values

4. Support for non-public members

5. Date Processing

6. Custom serialized Field names

I. Ignoring certain properties

Similar to the interface optimizations described at the beginning of this question, some attributes in the entity do not need to be serialized back, which can be used. The Json.NET serialization mode is introduced first: OptOut and OptIn

OptOut Default value, all public members of the class are serialized, and if you do not want to be serialized, you can use the attribute Jsonignore
OptIn By default, all members will not be serialized, and members of the class will only be serialized if they have attribute Jsonproperty, which is useful when the class has a large number of members, but only a subset of the data is needed by the client.

Only name attributes required

[Jsonobject (memberserialization.optin)] Public classPerson { Public intAge {Get;Set; } [Jsonproperty] Public stringName {Get;Set; }  Public stringSex {Get;Set; }  Public BOOLIsmarry {Get;Set; }  PublicDateTime Birthday {Get;Set; } }

Do not need to be married attribute

[Jsonobject (memberserialization.optout)] Public classPerson { Public intAge {Get;Set; }  Public stringName {Get;Set; }  Public stringSex {Get;Set; } [Jsonignore] Public BOOLIsmarry {Get;Set; }  PublicDateTime Birthday {Get;Set; } }

As you can see from the example above, it is easy to implement a requirement that does not return certain properties. 1. Add [Jsonobject (Memberserialization.optout)] to the entity Class 2. Add the [Jsonignore] description on the attribute that does not need to be returned.

Two. Default value handling

When serializing to ignore the default Value property can be determined by jsonserializersettings.defaultvaluehandling, the value is an enumeration value

Defaultvaluehandling.ignore
Ignore default values when serializing and deserializing
Defaultvaluehandling.include
Include default values when serializing and deserializing

[DefaultValue (tenpublicintgetset;}
New Ten " Zhang Sanfeng " " male " false New DateTime (199112)}; Jsonserializersettings jsetting=new  jsonserializersettings (); jsetting. defaultvaluehandling=defaultvaluehandling.ignore; Console.WriteLine (Jsonconvert.serializeobject (P, formatting.indented, jsetting));

The final result is as follows:

Three. Handling of NULL values

  A null-valued property needs to be ignored when serializing, Can be determined by jsonserializersettings.nullvaluehandling, and the Jsonserializersettings setting property is in effect for all properties in the serialization process, and you can use it if you want to take effect on a property individually Jsonproperty , the following will show two different ways

1.JsonSerializerSettings

Person p =Newperson {room=NULL, age =Ten, Name ="Zhang Sanfeng", Sex ="male", Ismarry =false, Birthday =NewDateTime (1991,1,2) }; Jsonserializersettings jsetting=Newjsonserializersettings (); jsetting. Nullvaluehandling=Nullvaluehandling.ignore; Console.WriteLine (Jsonconvert.serializeobject (P, formatting.indented, jsetting));

2.JsonProperty

Through the Jsonproperty property set method, you can implement a particular property to deal with the requirements, such as default value processing, NULL processing, custom attribute name processing, format processing. The above null-value processing implementation

[Jsonproperty (nullvaluehandling=publicgetset;}

Four. Support for non-public members

The default is to handle public members when serializing, and if you need to process non-public members, add the attribute "Jsonproperty" to the Member

Private int Get set; }

Five. Date processing

 For the Dateime type date format is more troublesome, the system will be formatted into the ISO date standard, but the actual use of most of the use of the process may be yyyy-mm-dd or YYYY-MM-DD HH:mm:ss Two formats of the date, The workaround is to change the datetime type to a string type itself, and then serialize it. If you do not want to modify the code, you can implement the following scenario.

Json.NET provides a isodatetimeconverter date conversion class that can be jsnconverter to achieve the appropriate date conversion

    [Jsonconverter (typeof(Isodatetimeconverter))]      Public Get set; }

But the Isodatetimeconverter date format is not what we want, we can inherit the class to implement its own date

     Public classChinadatetimeconverter:datetimeconverterbase {Private StaticIsodatetimeconverter Dtconverter =Newisodatetimeconverter {DateTimeFormat ="YYYY-MM-DD" };  Public Override ObjectReadjson (Jsonreader Reader, Type ObjectType,ObjectExistingvalue, Jsonserializer Serializer) {            returnDtconverter.readjson (Reader, ObjectType, existingvalue, serializer); }         Public Override voidWritejson (Jsonwriter writer,Objectvalue, Jsonserializer serializer)        {Dtconverter.writejson (writer, value, serializer); }    }

The implementation of a YYYY-MM-DD format conversion class, you can see just initialize isodatetimeconverter when the date format is YYYY-MM-DD, the following look at the effect

[Jsonconverter (typeof(Chinadatetimeconverter))]  Public Get set; }

Different conversion classes can be implemented according to your needs

Six. Custom serialized field names

the attribute name defined in the entity may not be the name you want, but you cannot change the entity definition, and you can customize the serialized field name at this time.

     " CName " )]     publicstringgetset; }

Back to top of the summary

Newtonsoft.json Serialization library for us to think of a lot of features, but also implemented a lot of features, in addition to the above six advanced usage, there are other special usage, you can go to the official website to study. Of course, my favorite feature here is the one that ignores the partial attribute serialization, and the small code churn realizes the optimization of the interface and improves the user experience.

If you think reading this blog gives you something to gain, just click on the " recommend " button in the lower right corner.
If you want to find my new blog more easily, click on " Follow me " in the green channel.
Because, my writing enthusiasm also inseparable from your affirmation support.

Thank you for your reading, if you are interested in the content of my blog, please continue to follow my following blog, I am the flame tail Diego.

Newtonsoft.json Advanced Usage

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.