Pergunta

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

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

Can Gson be configured to parse a timestamp-formatted date such as 1291158000000 into a java.util.Date object?

Foi útil?

Solução

You need to register your own deserializer for Dates.

I've created a small example below, in which the JSON string "23-11-2010 10:00:00" is deserialized to a Date object:

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());
    }
}

Outras dicas

With regards to Jackson, you can not only choose between numeric (timestamp) and textual serialization (SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS), but also define exact DateFormat to use for textual variant (SerializationConfig.setDateFormat). So you should be able to force use of something Gson recognizes, if it does not support ISO-8601 format Jackson defaults to using.

Also: Jackson works fine on Android, if you don't mind using it over Gson.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top