2

我的 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"

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

4

2 回答 2

0

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

  User user = jsonElement.getAsJsonObject().get( "user" ).getAsString();
  Date date = new Date(jsonElement.getAsJsonObject().get( "date" ).getAsLong());
于 2013-07-25T15:31:54.147 回答
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);
    }

}
于 2013-11-13T23:00:29.343 回答