I have a C# and java code that serializes an object into a JSON string to send between clients and the server. In C# I use Jil to serialize and deserialize objects. In java I use gson. Everything works fine until I work with C# DateTime object and Java Timestamp object. In C# DateTime serialization return Unix format like this:
{"timesent":"\/Date(1645856979963)\/"}
minimal reproducible example code:
class MyObject
{
public DateTime date;
public MyObject(DateTime date)
{
this.date = date;
}
}
static void Main(string[] args)
{
DateTime now = DateTime.Now;
MyObject myObject = new MyObject(now);
String json = Jil.JSON.Serialize<MyObject>(myObject);
Console.WriteLine(json);
//{"date":"\/Date(1648191236905)\/"}
}
meanwhile in Java Timestamp return format like this:
{"timesent":"Feb 20, 2022, 1:43:23 AM"}
PS: They are 2 different timestamps, I just want to say that the formats are different and cannot be deserialized by the other language
I tried converting Java Timestamp to Unix format with .getTime() and making it return a string like
"\\/Date(" + sql.getTimestamp("timesent").getTime() + ")\\/"
but it doesn't work because Jil throws an error:
Jil.DeserializationException: Expected character: '/'
but I can't just give it one \ because it is an escape character, so I have to give 2, but it doesn't take 2 and requires a / after a \
So how can I make Java gson serialization serializes Timestamp in Unix format so that the C# Jil can read it?
Edited: added reproducible code, I keep using Jil because it currently works for the app in C# and now I am just rewriting the app in Java but the client side is still in C#, I will try the suggestions!
Jil
do support anotherDateTime
format, namely the ISO-8601. Unfortunately, the developer specifically said they wont add more date formats. It can be used roughly the following way:However, if you are wiling to switch to
Newtonsoft.Json
, you can keep your current date format (Feb 20, 2022, 1:43:23 AM
) usingJsonConverter
attribute to tell the serializer to spew the date time in any format you want.First step to do that after installing
Newtonsoft.Json
, you should implement your own converter:The next step is to apply the
JsonConvert
attribute to the your class: