java – Gson:JsonSyntaxException on date

I tried to deserialize a JSON array using gson, but I'm getting a jsonsyntaxexception The JSON string is generated by using jsonresult Net mvc3 web service creation (meaning that I don't create JSON manually, it is created by a library that I know works on several other platforms)

This is 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);

Exception: invalid date format:

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

Anyone knows what happened

Solution

I found an answer here, but I found it strange that there was no simpler way Several other JSON libraries I use are supported by themselves Net JSON format I was surprised when gson didn't deal with it There must be a better way If anyone knows, please post it here It's all like this. This is my solution:

I created a custom jsondeserializer and registered it as a date type By doing so, gson will use my deserializer as the date type instead of the default If you want to serialize / deserialize in a custom way, you can do the same for any other type

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 create my gson object:

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

Now my gson object will be able to parse Net date format (millis since 1970)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>