Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson: JsonSyntaxException on date

Tags:

java

date

gson

I am trying to use Gson to deserialize a json array, but am currently getting a JsonSyntaxException. The json string was created by a .NET MVC3 web service using JsonResult (meaning, I am not manually creating the json, it is being created by a library which I know to work on several other platforms).

This is the json:

[{"PostID":1,"StudentID":39,"StudentName":"Joe Blow",
"Text":"Test message.","CreateDate":"\/Date(1350178408267)\/",
"ModDate":"\/Date(1350178408267)\/","CommentCount":0}]

This is the code:

public class Post {
   public int PostID;
   public int StudentID;
   public String StudentName;
   public String Text;
   public Date CreateDate;
   public Date ModDate;

   public Post() { }
}

Type listOfPosts = new TypeToken<ArrayList<Post>>(){}.getType();
ArrayList<Post> posts = new Gson().fromJson(json, listOfPosts);

The exception says that the date format is invalid:

com.google.gson.JsonSyntaxException: /Date(1350178408267)/

Anyone know what is going on?

like image 400
mtmurdock Avatar asked Oct 14 '12 02:10

mtmurdock


1 Answers

I found an answer here but I found it strange that there isn't an easier way. Several other json libraries I've used support the .NET json format natively. I was surprised when Gson didn't handle it. There must be a better way. If anyone knows of one, please post it here. All the same, this was my solution:

I created a custom JsonDeserializer and registered it for the Date type. By doing so, Gson will use my deserializer for the Date type instead of its default. The same can be done for any other type if you want to serialize/deserialize it in a custom way.

public class JsonDateDeserializer implements JsonDeserializer<Date> {
   public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
      String s = json.getAsJsonPrimitive().getAsString();
      long l = Long.parseLong(s.substring(6, s.length() - 2));
      Date d = new Date(l);
      return d; 
   } 
}

Then, when I am creating my Gson object:

Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDateDeserializer()).create();

Now my gson object will be capable of parsing the .NET date format (millis since 1970).

like image 139
mtmurdock Avatar answered Sep 22 '22 04:09

mtmurdock