I have to bind a Json object with a java object that has a Date. The Date format on my Json is the following:
2013-01-04T10:50:26+0000
And I'm using the GsonBulder as follow:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
but Im getting the following exception:
The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
com.google.gson.JsonSyntaxException: 2013-01-04T10:50:26+0000
at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:81)
.....
Caused by: java.text.ParseException: Unparseable date: "2013-01-04T10:50:26+0000"
at java.text.DateFormat.parse(DateFormat.java:337)
at com.google.gson.internal.bind.DateTypeAdapter.deserializeToDate(DateTypeAdapter.java:79)
I'm trying to load this request with Gson:
https://graph.facebook.com/me?fields=id,username,email,link,updated_time&access_token=accessToken
And the response is
{"id":"12345","username":"myusername","email":"myemail\u0040yahoo.it","link":"http:\/\/www.facebook.com\/mysusername","updated_time":"2013-01-04T10:50:26+0000"}
The Deserialization fails, because the quotes within the json String are missing.
The following works:
Gson gson= new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
String date = "\"2013-02-10T13:45:30+0100\"";
Date test = gson.fromJson(date, Date.class);
System.out.println("date:" + test);
Output:
date:Sun Feb 10 13:45:30 CET 2013
HTH
Edit Complete Example:
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class FacebookResponse {
int id;
String username;
String email;
String link;
Date updated_time;
@Override
public String toString() {
return "ID: " + id + " username: " + username + " email: " + email + " link: " + link + " updated_time: " + updated_time;
};
/**
* @param args
*/
public static void main(String[] args) {
String json = "{\"id\":\"12345\",\"username\":\"myusername\",\"email\":\"myemail\u0040yahoo.it\",\"link\":\"http://www.facebook.com/mysusername\",\"updated_time\":\"2013-01-04T10:50:26+0000\"}";
Gson gson= new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
FacebookResponse response = gson.fromJson(json, FacebookResponse.class);
System.out.println(response);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With