Jackson的`objectMapper.readValue(File)`在读取时修改了原始文件。

huangapple 未分类评论46阅读模式
英文:

Jackson objectMapper.readValue(File) modifes the original file while reading

问题

好的,以下是翻译好的部分:

似乎 readValue() 方法在读取后修改了文件。这发生在 Jackson 版本 2.9.8 和版本 2.9.10.3。

这是我调用以将对象序列化到文件的方法,它可以完美地进行序列化。

public void saveToFile() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writerFor(Type.class).withDefaultPrettyPrinter().writeValue(new File("C:\\Path\\To\\File.json"), object);
}

在反序列化时,我使用以下调用:

public Type restoreFromFile() throws IOException { 
    ObjectMapper objectMapper = new ObjectMapper();        
    Type restoredObj = objectMapper.readValue(new File("C:\\Path\\To\\File.json"), Type.class);
}

当调试器执行下一条指令(只是一个不会以任何方式触及文件但会迭代 restoredObj 的 for 循环)时,我的 File.json 更改,就好像另一个不遵循正常序列化使用的相同标签的 Type 类的 Obj 被序列化(它将一些值放为 null 并且不使用 @JsonIdentityInfo 进行序列化)。

请注意,第一次调用 restore() 方法时,Obj 被正确地反序列化,但如果我连续两次调用它,Obj 将以 null 值而不是正确的值进行反序列化。

英文:

It seems like the readValue() method modifies the file after reading. It happens with Jackson version 2.9.8 and version 2.9.10.3

This is the method I call to serialize the object to file and it serializes perfectly.

public void saveToFile() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writerFor(Type.class).withDefaultPrettyPrinter().writeValue(new File("C:\\Path\\To\\File.json"), object);
    }

When I deserialize I use this call:

public Type restoreFromFile() throws IOException { 
       ObjectMapper objectMapper = new ObjectMapper();        
       Type restoredObj = objectMapper.readValue(new File("C:\\Path\\To\\File.json"), Type.class);
    }

When the debugger passes to the next instruction (just a for loop that doesn't touch the file in any way, but iterates on the restoredObj) my File.json changes as if another Obj of class Type get serialized without following the same tags that the normal serialization uses (it puts some of the values at null and doesn't serialize using @JsonIdentityInfo).

Note that the Obj gets deserialized correctly the first time I call the restore() method, but if I call it twice in a row the Obj gets deserialized with null values instead of the correct ones.

huangapple
  • 本文由 发表于 2020年4月6日 05:44:24
  • 转载请务必保留本文链接:https://java.coder-hub.com/61049937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定