How to convert java timestamp time format to C# DateTime time format in JSON (C# Jil and Java gson)

598 Views Asked by At

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!

1

There are 1 best solutions below

0
On

Jil do support another DateTime format, namely the ISO-8601. Unfortunately, the developer specifically said they wont add more date formats. It can be used roughly the following way:

Jil.JSON.Serialize<MyObject>(myObject, Jil.Options.ISO8601)

However, if you are wiling to switch to Newtonsoft.Json, you can keep your current date format (Feb 20, 2022, 1:43:23 AM) using JsonConverter 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:

public class MyDateTimeConverter : IsoDateTimeConverter
{
   public MyDateTimeConverter()
   {
      base.DateTimeFormat = "MMM dd, yyyy, H:m:s tt";
   }
}

The next step is to apply the JsonConvert attribute to the your class:

class MyObject
{
  [JsonConvert(typeof(MyDateTimeConverter))]
  public DateTime date;
  public MyObject(DateTime date)
  {
    this.date = date;
  }
}