. Net object class and json conversion (implemented by the. net built-in Class Library), json.net

Source: Internet
Author: User
Tags string to json

. Net object class and json conversion (implemented by the. net built-in Class Library), json.net

In the previous article, we wrote that the conversion between the entity class and the json format in. net is not complete during the specific conversion today. In previous versions of jsonhelp, when converting an object class to a json format, the date format is converted to a timestamp format. This jsonhelp is updated here. To solve the problem of converting date fields. The Code is as follows:

JsonHelp. cs

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. runtime. serialization. json; using System. IO; using System. text. regularExpressions; namespace JsonTest {class JsonHelp {public JsonHelp () {// TODO: add constructor logic here // <summary> // serialize the object to a JSON string /// </summary> /// <typeparam name = "T"> Object type </typeparam> /// <param name = "obj"> Object entity </param> /// <returns> JSON string </returns> public static string GetJson <T> (T obj) {// remember to add reference System. serviceModel. web/*** if you do not add the above reference, System. runtime. serialization. json; Json is the bytes of the Oh **/DataContractJsonSerializer json = new DataContractJsonSerializer (typeof (T); using (MemoryStream MS = new MemoryStream () {json. writeObject (MS, obj); string jsonString = Encoding. UTF8.GetString (ms. toArray (); string pattern = @ "\/Date \ (\ d +) \ + \ d + \)\\/"; matchEvaluator matchEvaluator = new MatchEvaluator (ConvertJsonDateToDateString); Regex reg = new Regex (pattern); jsonString = reg. replace (jsonString, matchEvaluator); return jsonString ;}} /// <summary> /// restore the JSON string to an object // </summary> /// <typeparam name = "T"> Object Type </typeparam>/ // <param name = "jsonString"> JSON string </param> // <returns> Object entity </returns> public static T ParseFormJson <T> (string jsonString) {T obj = Activator. createInstance <T> (); string pattern = @ "\ d {4}-\ d {2}-\ d {2} \ s \ d {2 }: \ d {2 }:\ d {2} "; MatchEvaluator matchEvaluator = new MatchEvaluator (ConvertDateStringToJsonDate); Regex reg = new Regex (pattern); jsonString = reg. replace (jsonString, matchEvaluator); using (MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (jsonString) {DataContractJsonSerializer dcj = new DataContractJsonSerializer (typeof (T); return (T) dcj. readObject (MS) ;}/// <summary> /// time for Json serialization from/Date (1304931520336 + 0800) /convert to string // </summary> private static string ConvertJsonDateToDateString (Match m) {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 string 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 ;}}}

Test code:

using ConsoleApplication1.Models;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            using (var db = new JooWMSContext())             {                var admin = db.Admins.Where(p => p.ID > 0).OrderBy(p => p.ID);                foreach (var ad in admin)                 {                    Console.WriteLine(JsonTest.JsonHelp.GetJson<ConsoleApplication1.Models.Admin>(ad));                }                Console.ReadKey();            }        }    }}

EF is used when writing test code. A good tool is recommended here. EF Power Tools is currently available in beta4.

 

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.