Newtonsoft.json advanced usage 1. Ignore some properties 2. Handling of the default value 3. Handling of NULL values 4. Support for non-public members 5. Date processing 6. Custom serialized Field names

Source: Internet
Author: User
Tags net serialization



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:


// Serialize the DataTable
             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));





Use the string above to deserialize


 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]);
 }





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 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; }
    }





Do not need to be married attribute


    [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; }
    }





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 (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 = 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 = new Person { room=null,Age = 10, Name = "张三丰", Sex = "男", 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






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=nullvaluehandling.ignore)] public guest (n.);





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


[Jsonproperty] private int Height {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 DateTime Birthday {get; set;}


But the Isodatetimeconverter date format is not what we want, we can inherit the class to implement its 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);
        }
    }


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 DateTime Birthday {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.


     [Jsonproperty (propertyname = "CName")]     public string Name {get; set;}




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.






Newtonsoft.json advanced usage 1. Ignore some properties 2. Handling of the default value 3. Handling of NULL values 4. Support for non-public members 5. Date processing 6. Custom serialized Field names


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.