我正在尝试创建一种方法,该方法使用 Json 数据和 jackson 库来获取对象列表。如果我运行我的代码,我会收到错误:
java.lang.reflect.InaccessibleObjectException:无法使字段私有final int java.time.LocalDate.year可访问:模块java.base不会“打开java.time”到未命名模块@5c90e579
即使我的代码中有 JodaModul,为什么它会给我一个关于 LocalDate 的错误?
public static List<Tweet> getTweetsFile() throws Exception{
ObjectMapper mapper = new ObjectMapper().
registerModule(new JodaModule()).
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
File path = new File ("C:/Users/PC/eclipse-workspace/hw4/tw.json");
List<Tweet> myObjects3 = Arrays.asList(mapper.readValue(path, Tweet.class));
return myObjects3;
}
Run Code Online (Sandbox Code Playgroud)
它在我的文件中的样子:
[{"date":"2001-12-28","tweetNumber":1,"country":"England","comments":11,"message":"I like to watch anime and reading books","retweets":3,"username":"Isabelle","likes":55},{"date":"2003-05-11","tweetNumber":2,"country":"France","comments":25,"message":"I'm Viatnamese, but I live in France","retweets":30,"username":"Vin","likes":110}..
Run Code Online (Sandbox Code Playgroud)
它的顺序不正确,就像我的对象在其构造函数中的顺序一样,这可能是原因吗?
小智 7
我用这种方法解决了这个问题。首先,您必须使用 Json 数据中给定的日期格式创建 LocalDateTime 反序列化器。
class LocalDateTimeDeserializer implements JsonDeserializer < LocalDateTime > {
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return LocalDateTime.parse(json.getAsString(),
DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss").withLocale(Locale.ENGLISH));
}
Run Code Online (Sandbox Code Playgroud)
}
然后创建 GsonBuilder 类型的对象并使用 LocalDateDeserializer 对其进行调整。
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer());
Gson gson = gsonBuilder.setPrettyPrinting().create();
Run Code Online (Sandbox Code Playgroud)
小智 6
在 STS 或 eclipse 中,在默认 VM 参数中添加以下语句
--add-opens java.base/java.time=ALL-UNNAMED
默认 VM 参数路径:窗口 -> 首选项 -> 安装的 JRE -> 选择 jre -> 编辑
| 归档时间: |
|
| 查看次数: |
70498 次 |
| 最近记录: |