How to convert a Date between Jackson and Gson?

南楼画角 提交于 2019-12-22 06:33:44

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4322541/how-to-convert-a-date-between-jackson-and-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!