【发布时间】:2018-10-15 20:42:59
【问题描述】:
我需要使用 Gson 将字符串转换为对象:
gson.fromJson("{\"message\":\"any msg.\",\"individual\":{\"id\":100,\"citizenshipList\":[{\"date\":[2018,10,15,16,29,36,402000000]}]}}", Response.class)
在哪里
public class Response {
private String message;
private Individual individual;
}
public class Individual {
private Integer id;
private List<Citizenship> citizenshipList = new ArrayList<>();
}
public class Citizenship {
@DateTimeFormat(pattern="d::MMM::uuuu HH::mm::ss")
LocalDateTime date;
}
我收到这个错误
java.lang.IllegalStateException: 应为 BEGIN_OBJECT 但为 BEGIN_ARRAY 在第 1 行第 122 列路径 $.individual.citizenshipList[0].date
我也尝试过修改过的 Gson:
Gson gson1 = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@Override
public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject jo = json.getAsJsonObject();
return LocalDateTime.of(jo.get("year").getAsInt(),
jo.get("monthValue").getAsInt(),
jo.get("dayOfMonth").getAsInt(),
jo.get("hour").getAsInt(),
jo.get("minute").getAsInt(),
jo.get("second").getAsInt(),
jo.get("nano").getAsInt());
}
}).create();
但这给了我这个错误:
java.lang.IllegalStateException:不是 JSON 对象: [2018,10,15,16,29,36,402000000]
【问题讨论】:
-
为什么要将日期拆分成数组?并且没有被传递为
2018-10-15...? -
尝试使用
JsonArray而不是JsonObject。 -
不是我这样做是 Mockito mvc 和 MockHttpServletResponse .getContentAsString() 并且属性使用 localdatetime
标签: java json serialization gson