gpt4 book ai didi

deserialization - 适用于java.util.Date的Gson反序列化器

转载 作者:行者123 更新时间:2023-12-03 15:07:03 25 4
gpt4 key购买 nike

有人让Deserializer工作吗?我正在方法“反序列化”而不是元素中获得完整的JSON表达式?

    public static void main(String[] args) {
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(DummyObject.class, new JsonSerializer<Date>() {
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
System.out.println("serialize...");
return new JsonPrimitive(DateUtil.toString(src));
}
});
gb.registerTypeAdapter(DummyObject.class, new JsonDeserializer<Date>() {
DateFormat format = DateFormat.getInstance();

public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (!(json instanceof JsonPrimitive)) {
throw new JsonParseException("The date should be a string value");
}

try {
return format.parse(json.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
});

String jsonExp = "{\"createdDate\":\"2011-12-27T15:21:16\"}";
Gson g = gb.create();
DummyObject tf = g.fromJson(jsonExp, DummyObject.class);

}

最佳答案

Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssz")
.create();

关于deserialization - 适用于java.util.Date的Gson反序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8650913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com