将json的date属性反序列化为LocalDate
问题描述:
我正在尝试使用Gson反序列化格式为 2018-05-27的json中的date属性。我希望日期在反序列化后为LocalDate格式。
I am trying to de-serialize date attribute in json of format "2018-05-27" using Gson. I want date to be in LocalDate format after de-serialization.
对于json输入:
{
id:1,1,
name: test,
startDate: 2018-01-01,
endDate: 2018-01-05 ,
}
{ "id" : 1, "name" : "test", "startDate" : "2018-01-01", "endDate" : "2018-01-05", }
startDate和endDate出现错误:
I am getting error for startDate and endDate :
java.lang。 IllegalStateException:预期为BEGIN_OBJECT,但为STRING
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
答
我们做到这一点的方法是:
The way we can do this is :
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);