Newtonsoft. Json advanced usage, newtonsoft. json usage

Source: Internet
Author: User
Tags list of attributes

[Switch] Newtonsoft. Json advanced usage, newtonsoft. json usage

Mobile apps are fast and have a good experience. A project server interface on hand has performance problems and needs to be optimized. During multiple modifications to the interface, the object adds many fields for intermediate computing or storage, and then uses Newtonsoft. json serialized and returned data. After analyzing a simple list interface, each row of data returns 16 fields, but the mobile APP only uses seven of them, all the data in the remaining nine fields is redundant. If the data returned by the interface is 40 kb, that is, about 20 KB of data is invalid, 20 KB of data needs to be downloaded for about 1 second in 3G networks, if no invalid data is returned, it can save at least one second, greatly improving the user experience. This article will introduce some advanced usage of Newtonsoft. Json. You can modify a few codes to solve the above problems.

Reading directory

  • Newtonsoft. Json
  • Basic usage
  • Advanced usage
  • Summary
Return to Newtonsoft. Json at the top

During development, many data exchanges are transmitted in json format. When using Json, we often involve the use of several serialized objects:DataContractJsonSerializer,JavaScriptSerializerAndJson. NETNewtonsoft. Json. 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.

Complete API introduction, easy to use

 

Back to Top basic usage

Json. Net supports serialization and deserialization of DataTable, DataSet, Entity Framework, and Entity. The following are examples of serialization and deserialization.

DataTable:

// Serialize DataTable dt = new DataTable (); 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 (int I = 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 ));

Deserialization using the above string

 string json = JsonConvert.SerializeObject(dt); dt=JsonConvert.DeserializeObject<DataTable>(json); foreach (DataRow dr in dt.Rows) {   Console.WriteLine("{0}\t{1}\t{2}\t{3}\t", dr[0], dr[1], dr[2], dr[3]); }

The serialization of Entity is the same as that of DataTable.

Back to Top advanced usage

1. Ignore certain attributes

2. Processing of default values

3. Processing of null values

4. Support for non-public members

5. Date Processing

6. Custom serialized field name

7. dynamically determine whether the attribute is serialized

1. Ignore certain attributes

Similar to the Interface Optimization introduced at the beginning of this question, some attributes of an object do not need to be serialized and returned. You can use this feature. First, we will introduce the serialization modes of Json. Net: OptOut and OptIn.

OptOut Default Value. All public members in the class will be serialized. If you do not want to be serialized, you can use the JsonIgnore feature.
OptIn By default, all Members are not serialized, and only the Members marked with the JsonProperty property in the class are serialized. This is useful when the class has many Members but the client only needs a part of the data.

 

 

Only name attributes are required

    [JsonObject(MemberSerialization.OptIn)]    public class Person    {        public int Age { get; set; }        [JsonProperty]        public string Name { get; set; }        public string Sex { get; set; }        public bool IsMarry { get; set; }        public DateTime Birthday { get; set; }    }

No need to get married or not

    [JsonObject(MemberSerialization.OptOut)]    public class Person    {        public int Age { get; set; }        public string Name { get; set; }        public string Sex { get; set; }        [JsonIgnore]        public bool IsMarry { get; set; }        public DateTime Birthday { get; set; }    }

The above example shows that it is easy to implement the requirement of not returning certain attributes. 1. Add [JsonObject (MemberSerialization. OptOut)] to the object class. 2. Add the [JsonIgnore] description to the attributes that do not need to be returned.

Ii. Processing by default

You can use JsonSerializerSettings. DefaultValueHandling to determine whether to ignore the default attribute during serialization. This value is an enumerated value.

DefaultValueHandling.Ignore
Ignore default values during serialization and deserialization
DefaultValueHandling.Include
Including default values during serialization and deserialization

 

 

 

 [DefaultValue(10)] public int Age { get; set; }
Person p = new Person {Age = 10, Name = "Zhang Sanfeng", Sex = "male", IsMarry = false, Birthday = new DateTime (1991, 1, 2 )}; jsonSerializerSettings jsetting = new JsonSerializerSettings (); jsetting. defaultValueHandling = defavaluvaluehandling. ignore; Console. writeLine (JsonConvert. serializeObject (p, Formatting. indented, jsetting ));

The final result is as follows:

 

Iii. Processing of null values

  During serialization, You need to ignore the attribute whose value is NULL. You can use JsonSerializerSettings. nullValueHandling is used to determine. In addition, setting attributes through JsonSerializerSettings takes effect for all attributes in the serialization process. To apply attributes separately, use JsonProperty. The following two methods are shown:

1. JsonSerializerSettings

Person p = new Person {room = null, Age = 10, Name = "Zhang Sanfeng", Sex = "male", IsMarry = false, Birthday = new DateTime (1991, 1, 2)}; JsonSerializerSettings jsetting = new JsonSerializerSettings (); jsetting. nullValueHandling = NullValueHandling. ignore; Console. writeLine (JsonConvert. serializeObject (p, Formatting. indented, jsetting ));

2. JsonProperty

The JsonProperty attribute setting method can be used to meet special processing requirements for a property, such as default value processing, null value processing, custom attribute name processing, and formatting. The preceding Implementation of null value processing

 [JsonProperty(NullValueHandling=NullValueHandling.Ignore)] public Room room { get; set; }

 

4. Support for non-public members

By default, all public members are processed during serialization. To process non-public members, add the "JsonProperty" feature to the member"

 [JsonProperty] private int Height { get; set; }

 

5. Date Processing

 Formatting Dateime date is troublesome. The system will format the date as iso date standard, however, in actual use, most of the data may be in the yyyy-MM-dd Or yyyy-MM-dd HH: mm: ss format, the solution is to format the DateTime type to the string type and then serialize it. If you do not want to modify the code, you can use the following solution.

Json. Net provides the IsoDateTimeConverter date conversion class, which can be implemented through JsnConverter

    [JsonConverter(typeof(IsoDateTimeConverter))]    public DateTime Birthday { get; set; }

However, the IsoDateTimeConverter date format is not what we want. We can inherit this class to implement our own date

    public class ChinaDateTimeConverter : DateTimeConverterBase    {        private static IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" };        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)        {            return dtConverter.ReadJson(reader, objectType, existingValue, serializer);        }        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)        {            dtConverter.WriteJson(writer, value, serializer);        }    }

You have implemented a yyyy-MM-dd format conversion class. You can see that only the date format given when IsoDateTimeConverter is initialized is yyyy-MM-dd. The following figure shows the effect.

[JsonConverter(typeof(ChinaDateTimeConverter))]public DateTime Birthday { get; set; }

You can implement different conversion classes as needed.

 

6. Custom serialized Field Names

The property name defined in the object may not be the name you want, but cannot be changed. In this case, you can customize the serialized field name.

     [JsonProperty(PropertyName = "CName")]     public string Name { get; set; }

 

7. dynamically determine whether the attribute is serialized

  This is to meet the special demand of @ rice grain. In some scenarios, the attributes A, B, and C may be output in scenario A, and the attributes E and F may be output in scenario B. Although this requirement does not exist in reality, json.net still supports this feature.

Inherit the default defaconcontractresolver class and pass in the attributes to be output

Public class LimitPropsContractResolver: DefaultContractResolver {string [] props = null; public LimitPropsContractResolver (string [] props) {// specifies the list of attributes to be serialized this. props = props;} // REF: http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size.aspx protected override IList <JsonProperty> CreateProperties (Type type, MemberSerialization memberSerialization) {IList <JsonProperty> list = base. createProperties (type, memberSerialization); // only the returned list with the listed attributes is retained. where (p => props. contains (p. propertyName )). toList ();}}
        public int Age { get; set; }        [JsonIgnore]        public bool IsMarry { get; set; }        public string Sex { get; set; }
      JsonSerializerSettings jsetting=new JsonSerializerSettings();      jsetting.ContractResolver = new LimitPropsContractResolver(new string[] { "Age", "IsMarry" });      Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.Indented, jsetting));

Use a custom parsing class to output only the "Age" and "IsMarry" attributes and check the final result. only the Age attribute is output. Why is the IsMarry attribute not output?

 

If you see the above results and want to implement pc-side serialization, it's easy to serialize the other part on the mobile phone. Let's change the code to implement it.

  string[] propNames = null;  if (p.Age > 10)  {    propNames = new string[] { "Age", "IsMarry" };  }  else  {      propNames = new string[] { "Age", "Sex" };  }  jsetting.ContractResolver = new LimitPropsContractResolver(propNames);  Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.Indented, jsetting));
Back to Top Summary

Newtonsoft. Json serialization library has many features for us and has implemented many features. In addition to the advanced usage described above, there are other special usage which can be learned on the official website. Of course, my favorite feature at present is the function that ignores partial property serialization. Small code changes have optimized the interface and improved the user experience.

 

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.