2

I access a web service in a POST method. I need to send to the server a json serialized object. In my Android class I have some string fields and a Date field. This Date field gets serialized like this:

.... TouchDateTime":"Oct 6, 2010 5:55:29 PM"}"

but to be compatible with the web service I need to have it like:

"TouchDateTime":"\/Date(928138800000+0300)\/"

I found an interesting article about Deserialization in here: http://benjii.me/2010/04/deserializing-json-in-android-using-gson/ I think I need to do something like this. Could you give me a helping hand ?

Alin
  • 14,809
  • 40
  • 129
  • 218
  • Also, you could see here: http://stackoverflow.com/questions/206384/how-to-format-a-json-date – Cody Dec 28 '11 at 18:36
  • I used http://stackoverflow.com/a/2453820/8524 to get the TimeZone offset for the above. How did you do it? – Diederik May 30 '12 at 14:55

2 Answers2

8

In case anybody needs it, here is how I did it. 1. Create a new class DateSerializer and put in it:

import java.lang.reflect.Type;
import java.util.Date;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class DateSerializer implements JsonSerializer<Object> 
{
    public JsonElement serialize(Date date, Type typeOfT, JsonSerializationContext context)
    {
        return new JsonPrimitive("/Date(" + date.getTime() + ")/");
    }

    public JsonElement serialize(Object arg0, Type arg1,
            JsonSerializationContext arg2) {

        Date date = (Date) arg0;
        return new JsonPrimitive("/Date(" + date.getTime() + ")/");
    }
}

And here is how I use it:

   public static JSONObject Object(Object o){
    try {
        GsonBuilder gsonb = new GsonBuilder();
        DateSerializer ds = new DateSerializer();
        gsonb.registerTypeAdapter(Date.class, ds);
        Gson gson = gsonb.create();


        return new JSONObject(gson.toJson(o));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}
Alin
  • 14,809
  • 40
  • 129
  • 218
  • Can I ask why you add "Date()" and the / character? I've seen it in numerous examples but I just can't wrap my head around it. Why not just transfer the milliseconds as a number? Thanks – JayPea Nov 14 '11 at 21:26
  • @JayPea because that is part of the retarded WCF .NET DateTime format. If you see it in JSON, it's likely the API is also exceptionally retarded in other ways. – straya Aug 05 '15 at 01:12
0

If someone needs both serialization and deserialization, I've prepared a GsonHelper for it: How to parse .net DateTime received as json string into java's Date object

Community
  • 1
  • 1
peter.bartos
  • 11,855
  • 3
  • 51
  • 62