Gson:无法解析日期

时间:2013-01-07 14:05:08

标签: java json gson

我的json输入如下:

{ user: "sample-user", date : 1225864800 }

我的DateDeserializer类是:

private class DateDeserializer implements JsonDeserializer<Date>
{
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException
    {
        System.out.println("Deserializer...");
        return new Date(json.getAsJsonPrimitive().getAsLong());
    }
}

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());
gson.fromJson(new FileReader("input.json"), MyType.class);

即使在设置完所有内容后,我也会

java.text.ParseException: Unparseable Date: "1225864800"

我在这里做错了吗?请帮忙。

2 个答案:

答案 0 :(得分:0)

您尝试将整个Json结构反序列化为Date,而不仅仅是日期字段。你需要这样的东西:

  User user = jsonElement.getAsJsonObject().get( "user" ).getAsString();
  Date date = new Date(jsonElement.getAsJsonObject().get( "date" ).getAsLong());

答案 1 :(得分:0)

您可以为整个MyType类编写适配器,以便您可以在其他位置(如果有)保持标准日期反序列化,并仅在MyType内限制特定的反序列化。

为了更好地解释我的意思,这里是您可以复制并粘贴和运行的代码:

package stackoverflow.questions.q14197557;

import java.lang.reflect.Type;
import java.util.Date;

import com.google.gson.*;

public class Q14197557 {

    public static class MyType {

        String user;
        Date date;
        @Override
        public String toString() {
            return "MySample [user=" + user + ", date=" + date + "]";
        }

    }

    public static class MySampleDeserializer implements JsonDeserializer<MyType> {
        public MyType deserialize(JsonElement json, Type typeOfT,
                JsonDeserializationContext context) throws JsonParseException {

           if (json == null)
               return null;
           else {
               MyType s = new MyType();
               s.user = json.getAsJsonObject().get("user").getAsString();
               s.date = new Date(json.getAsJsonObject().get("date").getAsLong());
               return s;

           }

        }
    }

    public static void main(String[] args) {

        String json = "{ user: \"sample-user\", date : 1225864800 }";
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(MyType.class, new MySampleDeserializer());
        MyType s = gsonBuilder.create().fromJson(json, MyType.class);

        System.out.println("My Type: " + s);
    }

}