我正在尝试使用Gson反序列化格式为“ 2018-05-27”的json中的date属性。我希望反序列化后的日期为LocalDate格式。
对于json输入:
{ “ id”:1 “ name”:“ test”, “ startDate”:“ 2018-01-01”, “ endDate”:“ 2018-01-05”, }
startDate和endDate出现错误:
java.lang.IllegalStateException:预期为BEGIN_OBJECT,但为STRING
答案 0 :(得分:1)
我们可以做到的方式是:
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);