我在尝试反序列化 gson LocalDate 时遇到问题。 我还有接下来的 2 个适配器:
public class LocalDateSerializer implements JsonSerializer < LocalDate > {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");
@Override
public JsonElement serialize(LocalDate localDate, Type srcType, JsonSerializationContext context) {
return new JsonPrimitive(formatter.format(localDate));
}
}
和
public class LocalDateDeserializer implements JsonDeserializer < LocalDate > {
@Override
public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return LocalDate.parse(json.getAsString(),
DateTimeFormatter.ofPattern("d-MMM-yyyy").withLocale(Locale.ENGLISH));
}
}
我尝试对对象“任务”进行简单的序列化,该对象具有 LocalDate 类型的字段开始时间。
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateSerializer());
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateDeserializer());
Gson gson = gsonBuilder.setPrettyPrinting().create();
LocalDate now=LocalDate.now();
Task task=new Task();
task.setID(1);
task.setDuration(2);
task.setID_Proiect(1);
task.setStarttime(now);
JSONObject json=new JSONObject(task);
String aux1=gson.toJson(json);
System.out.println(aux1);
Task t2=gson.fromJson(aux1,Task.class);
我收到错误
无法使字段“java.time.LocalDateTime#date”可访问;任何一个 更改其可见性或为其声明编写自定义 TypeAdapter 类型
你能告诉我这段代码有什么问题吗?我知道这可能是一个菜鸟问题,但我确实需要帮助来提高我的技能。泰
在 java 升级 11 到 17 期间,我在使用 gson 反序列化 java.time.Instant 时遇到了同样的问题,请参阅 gson 文档,了解发生这种情况的原因: https://github.com/google/gson/blob/main/UserGuide.md#gsons-expose
解决方案: 使用 -
new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
创建 Gson