Newtonsoft.json Time Formatting problems

Source: Internet
Author: User
Tags net serialization

Global Settings for 1.WPF loading

New Newtonsoft.Json.JsonSerializerSettings ();             New Func<jsonserializersettings> (() =            {                =  Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;                 " YYYY-MM-DD HH:mm:ss " ;                 return setting;            });

2.newtonsoft.json serialization and deserialization of time formats

Links: http://www.cnblogs.com/litian/p/3870975.html

1.JSON serialization

String jsonstr= jsonconvert.serializeobject (Entity);

eg

A a=new a (); A.name= "Elain00"; a.hobby= "Eat eat"; string Jsonstr=jsonconvert.serializeobject (a);

2.JSON deserialization

String jsonstr = "jsonstring";
Class model = jsonconvert.deserializeobject<class> (JSONSTR);

eg

String jsonstr= ' {\ ' name\ ': \ ' elaine00\ ', \ ' hobby\ ': \ ' eat eat\ '} '; A a=jsonconvert.deserializeobject<a> (JSONSTR);

3. Time format processing

Isodatetimeconverter TimeFormat = new Isodatetimeconverter ();                    Timeformat.datetimeformat = "Yyyy-mm-dd HH:mm:ss";                    Response.Write (Jsonconvert.serializeobject (BLL). Getmodellist (strwhere), Newtonsoft.Json.Formatting.Indented, TimeFormat);

4. Extension methods

public static class Newtonjsonhelper    {public        static string SerializeObject (This object obj)        {            return Jsonconvert.serializeobject (obj, formatting.indented, new jsonserializersettings{                referenceloophandling = Referenceloophandling.ignore});        }        public static T-deserializeobject<t> (This string data)        {            return jsonconvert.deserializeobject<t> (data, new jsonserializersettings            {                referenceloophandling = Referenceloophandling.ignore            });        }    }

5. Date Processing

public class logentry{Public  string Details {get; set;}  Public DateTime logdate {get; set;}} public void Writejsondates () {  LogEntry entry = new LogEntry  {    logdate = new DateTime (2, 0, 0, 0, Dat ETIMEKIND.UTC),    Details = "Application started."  };  Default as of Json.NET 4.5  string Isojson = Jsonconvert.serializeobject (entry);  {"Details": "Application started.", "logdate": "2009-02-15t00:00:00z"}  jsonserializersettings microsoftdateformatsettings = new Jsonserializersettings  {    dateformathandling = Dateformathandling.micro
public class Limitpropscontractresolver:defaultcontractresolver {private string[] props = null;        Public Limitpropscontractresolver (string[] props) {this.props = props;         } protected override ilist<jsonproperty> Createproperties (type type, memberserialization memberserialization) {ilist<jsonproperty> list = base.            Createproperties (type, memberserialization);            Isodatetimeconverter ISO = new Isodatetimeconverter () {DateTimeFormat = "yyyy-mm-dd HH:mm:ss"};            ilist<jsonproperty> listwithconver = new list<jsonproperty> (); foreach (var item in list) {if (props. Contains (item. PropertyName)) {if (item). Propertytype.tostring (). Contains ("System.DateTime")) {item.                    Converter = ISO;                } listwithconver.add (item);  }            }          return listwithconver; }    }}

Softdateformat  };  String Microsoftjson = Jsonconvert.serializeobject (entry, microsoftdateformatsettings);  {"Details": "Application started.", "logdate": "\/date (1234656000000) \"}  string Javascriptjson = Jsonconvert.serializeobject (Entry, New Javascriptdatetimeconverter ());  {"Details": "Application started.", "logdate": New Date (1234656000000)}}

2.JSON deserialization of string jsonstr = "jsonstring"; Class model = jsonconvert.deserializeobject<class> (JSONSTR), eg:string jsonstr= ' "{\ ' name\ ': \ ' elaine00\ ', \ ' Hobby\ ': \ ' eat eat\ '}; A a=jsonconvert.deserializeobject<a> (JSONSTR);

This is typically done for value types, and is determined by setting the value of jsetting.defaultvaluehandling, which is an enumeration type.

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

Set the default value for the member, use the "DefaultValue" attribute, and of course, don't forget to introduce the namespace "System.ComponentModel", assuming the employee's age defaults to 30

        [DefaultValue (+)]        public int Age {get; set;}

When serializing I want to ignore the member that is the default value

            Staff Jack = new Staff {Name = ' jack ', age = $, Gender = ' Male ', departmentname = ' personnel Department ', Leader = null };            var jsetting = new Jsonserializersettings ();            jsetting.defaultvaluehandling = Defaultvaluehandling.ignore;            String json = Jsonconvert.serializeobject (jack,jsetting);            Console.WriteLine (JSON);

Results:

3. Ignore certain properties

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.

If the customer only needs the employee's name, this

    [Jsonobject (Newtonsoft.Json.MemberSerialization.OptIn)]    public class staff    {        [jsonproperty] public        string Name {get; set;}        public int Age {get; set;}        public string Gender {get; set;}        public string Departmentname {get; set;}        Public staff Leader {get; set;}    }

Serialization:

            Staff Jack = new Staff {Name = ' jack ', age = $, Gender = ' Male ', departmentname = ' personnel Department ', Leader = null };            String json = Jsonconvert.serializeobject (Jack);

Results:

If the customer does not want the employee's leadership information

    public class staff    {public        string Name {get; set;}        public int Age {get; set;}        public string Gender {get; set;}        public string Departmentname {get; set;}        [Jsonignore]        Public staff Leader {get; set;}    }

Serialization:

            Staff Tom = new Staff {Name = ' Tome ', age = $, Gender = "Male", Departmentname = "Personnel Department"};            Staff Jack = new Staff {Name = ' jack ', age = $, Gender = ' Male ', departmentname = ' personnel Department ', Leader = Tom} ;            String json = Jsonconvert.serializeobject (jack);            Console.WriteLine (JSON);

Results:

4. Support for non-public members

When Json.NET serializes an object, only the public member is serialized by default, and the attribute "Jsonproperty" is added to the member if you want the non-public member to be serialized as well.

5. Date processing

The jsonconverters is used when serializing and deserializing. Jsonconverters allows manual control of the JSON. This is useful when the structure of the JSON is complex and you want to change how a type is serialized. When a jsonconverters is added to Jsonserializer, it checks each value to be serialized and deserialized and returns Canconvert, if true, Jsonconverter reads and writes the value; While Jsonconverter allows you to fully control the value of JSON, many of the Json.NET serialization features are limited, such as type names and reference handling. All the JsonConvert are under the namespace "Newtonsoft.Json.Converters"

5.1IsoDateTimeConverter and Javascriptdatetimeconverter

This is the json.net in the two processing date class, the default is Isodatetimeconverter, its format is "yyyy"-' mm '-' dd ' T ' HH ': ' mm ': ' SS. Fffffffk ". The other is Javascripttimeconverter, whose format is" new Date (Ticks) ", which actually returns a JavaScript date object.
There are two ways to apply jsonconverter, changing the behavior of JSON serialization and deserialization.

5.1.1 If you want to serialize the date format is unified, you can consider the following ways

Suppose we add two date-type members to the employee, the date of birth and the date of entry

    public class staff    {public        string Name {get; set;}        public int Age {get; set;}        public string Gender {get; set;}        public string Departmentname {get; set;}        Public staff Leader {get; set;}        Public DateTime BirthDate {get; set;}        Public DateTime employmentdate {get; set;}    }

Our customer requires a date type member to return a JavaScript date object

            Staff Jack = new Staff {Name = ' jack ', age = $, Gender = ' Male ',                departmentname = ' personnel Department ', BirthDate = new DateTime (1982,2,12), employmentdate = new DateTime (2010,12,12)};            String json = Jsonconvert.serializeobject (jack,new javascriptdatetimeconverter ());            Console.WriteLine (JSON);

Results:

5.1.2 If you want different date type members to be serialized, display them in a different form.

Our customers now require the date of birth to be returned in the "ISO" standard date format, and the date of entry is returned in the format of the JavaScript Date object, modifying our Employee class

    public class staff    {public        string Name {get; set;}        public int Age {get; set;}        public string Gender {get; set;}        public string Departmentname {get; set;}        Public staff Leader {get; set;}        [Jsonconverter (typeof (Isodatetimeconverter))]        Public DateTime BirthDate {get; set;}        [Jsonconverter (typeof (Javascriptdatetimeconverter))]        Public DateTime employmentdate {get; set;}    }

Yes, with the feature "jsonconverter" to achieve differentiated
Serialization:

            Staff Jack = new Staff {Name = ' jack ', age = $, Gender = ' Male ',                departmentname = ' personnel Department ', BirthDate = new DateTime (1982,2,12), employmentdate = new DateTime (2010,12,12)};            String json = Jsonconvert.serializeobject (jack);            Console.WriteLine (JSON);

Results:

5.2 Custom Date formats

Customers now request that the desired date format is in line with the Chinese custom format. The requested format is "April 20, 2012". The challenge came, there was no progress without the challenge, I liked the challenge. It's no use talking about it. I have considered two ways to solve this problem.
Idea One:
Studied the above two date processing classes, found that they have inherited the base class "Datetimeconverterbase", so we can refer to the "isodatetimeconverter" implementation of the way, Create a new converter class to process the date format yourself. The disadvantage of this approach is that it may take a lot of time to study, and it is much more laborious. The advantage is that you can control the date format arbitrarily.
Idea two:
I also studied "Isodatetimeconverter" and found that its date format is actually due to the internal Defaultdatetimeformat = "yyyy '-' mm '-' dd ' T ' HH ': ' mm ': ' SS. Fffffffk "causes, and it also provides the property" DateTimeFormat "to modify the date style, as long as we write in this format OK.

            Staff Jack = new Staff {Name = ' jack ', age = $, Gender = ' Male ',                departmentname = ' personnel Department ', BirthDate = new DateTime (1982,2,12), employmentdate = new DateTime (2010,12,12)};            Isodatetimeconverter Dtconverter = new Isodatetimeconverter {DateTimeFormat = "yyyy ' MM ' dd ' Day '"};            String json = Jsonconvert.serializeobject (jack,dtconverter);            Console.WriteLine (JSON);

Results:

6.FAQ 1. How do I customize a serialized field name?By default, the field names in the results of the json.net serialization are consistent with the names of the properties in the class. If you want to customize the field names after serialization, you can use Jsonproperty. For example:
public class Person {public       int Id {get; set;}       public string Name {get; set;}}

The default serialization result is: {"Id": 1, "Name": "Yang Too"}, if you do not want to use the default field name, you can use the following method:

public class person{       [Jsonproperty (propertyname = "PersonId")] public       int Id {get; set;}       [Jsonproperty (propertyname = "PersonName")]       public string Name {get; set;}}

The result of this serialization is: {"PersonId": 1, "personname": "Yang Over"}

Newtonsoft.json Time Formatting problems

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.