Reputation: 10476
I'm trying to deserilize an object the following code, and I'm wondering what the proper regex would be to replace json dates. When I run the following code, the regex never gets triggered. I'm 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;
}
Upvotes: 4
Views: 2572
Reputation: 2954
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;
}
}
}
Upvotes: 5
Reputation: 100547
@"\\/Date
portion look wrong. It probably should be either @"\/Date..."
or "\\/Data..."
. (same for trailing "...\\/"
)
Upvotes: 0