views:

23

answers:

1

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 ?

A: 

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