C # / ASP.NET JSON date deserialize

I am trying to deserialize an object with the following code, and I am wondering which correct regular expression will replace json dates. When I run the following code, the regular expression never runs. I am using the standard JSON date format inside the json string.

{ "UniqueId": "1000000003", "Id": 3, "ModifyTimestamp": "/Date(1338857699743)/" } string json = // see above string p = @"\\/Date\((\d+)\+\d+\)\\/"; MatchEvaluator matchEvaluator = new MatchEvaluator(convertJsonDateToDateString); Regex reg = new Regex(p); json = reg.Replace(json, matchEvaluator); JavaScriptSerializer serializer = new JavaScriptSerializer(); Student student = serializer.Deserialize<Student>(json) as Student; public 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; } 
+4
source share
2 answers

Here is a fully working solution:

 using System; using System.Windows.Forms; using System.Text.RegularExpressions; namespace ResolveOverlapIssue { public partial class Form1 : Form { private static void DoSomethingElse<T>(ref T Id) { int i = 00; } public Form1() { InitializeComponent(); string json = "{" + "UniqueId: 1000000003," + "Id: 3," + "ModifyTimestamp: /Date(1338857699743)/" + "}"; MatchEvaluator matchEvaluator = ConvertJsonDateToDateString; var reg = new Regex(@".Date\(\d+\)\/."); json = reg.Replace(json, matchEvaluator); } public static string ConvertJsonDateToDateString(Match m) { var dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); dt = dt.ToLocalTime(); var result = dt.ToString("yyyy-MM-dd HH:mm:ss"); return result; } } } 
+5
source

@"\\/Date part looks wrong. It should probably be either @"\/Date..." or "\\/Data..." (the same for trailing "...\\/" )

0
source

Source: https://habr.com/ru/post/1416081/


All Articles