How to convert date between Jackson and Gson?

In our Spring-configured REST server, we use Jackson to convert the object to Json. This object contains several java.util.Date objects.

When we try to deserialize it on an Android device using the Gson fromJson method, we get "java.text.ParseException: Unparseable date". We tried serializing the date to a timestamp corresponding to the milliseconds since 1970, but getting the same exception.

Is it possible to configure Gson to parse a date in timestamp format, e.g. 1291158000000, into a java.util.Date object?

+5
source share
2 answers

.

, JSON "23-11-2010 10:00:00" Date:

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;


public class Dummy {
    private Date date;

    /**
     * @param date the date to set
     */
    public void setDate(Date date) {
        this.date = date;
    }

    /**
     * @return the date
     */
    public Date getDate() {
        return date;
    }

    public static void main(String[] args) {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {

                SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                String date = json.getAsJsonPrimitive().getAsString();
                try {
                    return format.parse(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Gson gson = builder.create();
        String s = "{\"date\":\"23-11-2010 10:00:00\"}";
        Dummy d = gson.fromJson(s, Dummy.class);
        System.out.println(d.getDate());
    }
}
+6

Jackson, (timestamp) (SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS), DateFormat (SerializationConfig.setDateFormat). , , Gson, ISO-8601, Jackson .

: Android, Gson.

+1

All Articles