将 json 的日期属性反序列化为 LocalDate
Deserialize date attribute of json into LocalDate
我正在尝试使用 Gson 反序列化格式为“2018-05-27”的 json 中的日期属性。我希望反序列化后的日期为 LocalDate 格式。
对于json输入:
{
"id" : 1,
"name" : "test",
"startDate" : "2018-01-01",
"endDate" : "2018-01-05",
}
我收到 startDate 和 endDate 的错误:
java.lang.IllegalStateException:应为 BEGIN_OBJECT 但实际为 STRING
我们可以这样做的方法是:
private static final Gson gson = new GsonBuilder().registerTypeAdapter(LocalDate.class, new JsonDeserializer<LocalDate>() {
@Override
public LocalDate deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return LocalDate.parse(json.getAsJsonPrimitive().getAsString());
}
}).create();
然后是
YourClassName yourClassObject = gson.fromJson(msg, YourClassName.class);
我正在尝试使用 Gson 反序列化格式为“2018-05-27”的 json 中的日期属性。我希望反序列化后的日期为 LocalDate 格式。
对于json输入:
{ "id" : 1, "name" : "test", "startDate" : "2018-01-01", "endDate" : "2018-01-05", }
我收到 startDate 和 endDate 的错误:
java.lang.IllegalStateException:应为 BEGIN_OBJECT 但实际为 STRING
我们可以这样做的方法是:
private static final Gson gson = new GsonBuilder().registerTypeAdapter(LocalDate.class, new JsonDeserializer<LocalDate>() {
@Override
public LocalDate deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return LocalDate.parse(json.getAsJsonPrimitive().getAsString());
}
}).create();
然后是
YourClassName yourClassObject = gson.fromJson(msg, YourClassName.class);