How to serialize and deserialize time in JSON in ASP. NET

Source: Internet
Author: User
Tags add time

Processing of JSON serialization and deserialization Date and Time

JSON format does not support date and time. The datetime value is displayed as a JSON string in the format of "/date (700000 + 0500)/", where the first number (700000 In the example provided) it is the number of milliseconds that have elapsed since midnight, January 1, January 1, 1970 by normal time (non-timeout. This number can be a negative number to indicate the previous time. The example contains "+ 0500", which indicates that the time belongs to the local type, that is, it should be converted to the local time zone during deserialization. If this part does not exist, the time is deserialized to UTC.

1. Add an object class to demonstrate the differences before and after time serialization

Public class person
{
Public string name {set; get ;}
Public int age {set; get ;}
Public datetime birthday {set; get ;}
}

2. Main program call:

Public class Program
{

Static void main (string [] ARGs)
{
Person P = new person ();
P. Name = "akwwl ";
P. Age = 25;
P. Birthday = datetime. now;
String JSON = jsonhelper. objecttojson (p); // the serialization method.
Console. writeline (JSON );
Console. readkey ();

}

}

If the time is not serialized, The serialized result is:

{"Age": 25, "Birthday": "\/date (1348540465218 + 0800) \/", "name": "akwwl "}

3. Next we will add time serialization in the original serialization processing class.

Public class jsonhelper
{

Public static string objecttojson <t> (T)
{
Using (memorystream MS = new memorystream ())
{
Datacontractjsonserializer serializer = new datacontractjsonserializer (typeof (t ));
Serializer. writeobject (MS, t );
Ms. Position = 0;
Using (streamreader reader = new streamreader (MS ))
{
String JSON = reader. readtoend ();
String P = @ "\/date \ (\ D +) \ + \ D + \)\\/";
Matchevaluator evaluator = new matchevaluator (convertjsondatetodatestring );

// Process the time. You need to reference system. Text. regularexpressions; namespace
RegEx Reg = new RegEx (P );
JSON = reg. Replace (JSON, evaluator );
Return JSON;
}

}
}

Public static t jsontoobject <t> (string JSON)
{
String P = @ "\ D {4}-\ D {2}-\ D {2} \ s \ D {2 }:\ d {2 }: \ D {2 }";
Matchevaluator evaluator = new matchevaluator (convertdatestringtojsondate); // process the time
RegEx Reg = new RegEx (P );
JSON = reg. Replace (JSON, evaluator );
Using (memorystream MS = new memorystream (encoding. Unicode. getbytes (JSON )))
{
Datacontractjsonserializer serializer = new datacontractjsonserializer (typeof (t ));
T data = (t) serializer. readobject (MS );
Return data;
}
}

/// <Summary>
/// Convert the JSON time to a time character
/// </Summary>

Private Static string convertjsondatetodatestring (Match m) // serialize the time
{
String result = string. empty;
Datetime dt = new datetime (1970, 1, 1 );
Dt = DT. addmilliseconds (long. parse (M. Groups [1]. Value ));
Dt = DT. tolocaltime ();
Result = DT. tostring ("yyyy-mm-dd hh: mm: SS ");
Return result;
}

/// <Summary>
/// Convert the time character to JSON time
/// </Summary>

Private Static string convertdatestringtojsondate (Match m)
{
String result = string. empty;
Datetime dt = datetime. parse (M. Groups [0]. value );
Dt = DT. touniversaltime ();
Timespan Ts = DT-datetime. parse ("1970-01-01 ");
Result = string. Format ("\/date ({0} + 0800) \/", ts. totalmilliseconds );
Return result;
}

}

Main program call:

Public class Program
{

Static void main (string [] ARGs)
{
Person P = new person ();
P. Name = "akwwl ";
P. Age = 25;
P. Birthday = datetime. now;
String JSON = jsonhelper. objecttojson (p); // the serialization method.
Console. writeline (JSON );
Console. readkey ();

}

}

Output result:
{"Age": 25, "Birthday": "2012-09-25 10:50:00", "name": "akwwl "}

The preceding figure shows how to process time serialization and deserialization in JSON.

 

 

 

 

 

 

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.