Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Date between Jackson and Gson?

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?

like image 612
Gober Avatar asked Dec 01 '10 08:12

Gober


People also ask

How do I change date format in Gson?

We can create a Gson instance by creating a GsonBuilder instance and calling with the create() method. The GsonBuilder(). setDateFormat() method configures Gson to serialize Date objects according to the pattern provided.

How do you convert Gson to Jackson?

Gson fromJson() method is useful to parse Json into Java objects. For Jackson, we need to create object of ObjctMapper class that provides the functionality for reading or writing JSON. To convert a JSON into Java Object, readValue() function is useful and for vice-versa, use writeValueAsString() function.

What is the difference between Jackson and Gson?

If you're concerned about parsing speed for your JSON library, choose Jackson for big files, GSON for small files, and JSON. simple for handling both.

Is Gson faster than Jackson?

Looking at the average result for all the test runs across all the files, GSON is the winner here, with JSON. simple and JSONP taking a distinct second and third place, respectively. Jackson came in 2nd to last. So despite not being the fastest on any single file, JSON.


1 Answers

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());
    }
}
like image 80
dogbane Avatar answered Oct 17 '22 13:10

dogbane