Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

java - Gson: JsonSyntaxException on date

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...