java - 杰克逊在序列化过程中添加了不存在的字段
问题描述
映射器:
public static ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.enable(SerializationFeature.INDENT_OUTPUT);
要序列化的类:
@Builder(builderClassName = "GooglePlayGameBuilder", toBuilder = true)
@JsonDeserialize(builder = GooglePlayGame.GooglePlayGameBuilder.class)
public final class GooglePlayGame {
@JsonProperty("Title") private final String title;
@JsonProperty("Genre") private final String genre;
@JsonProperty("Price") private final String price;
@JsonProperty("Last updated") private final String lastUpdated;
@JsonProperty("Current version") private final String currentVersion;
@JsonProperty("Requirements") private final String requiresAndroid;
@JsonProperty("IAP") private final String IAP;
@JsonProperty("Contacts") private final String devEmail;
...
将对象添加到地图,然后我想序列化我的地图:
public static volatile ConcurrentMap<String, GooglePlayGame> games = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER);
写入文件:
public static void saveLibraryToFile(){
try {
mapper.writeValue(new File(LIBRARY_FILENAME), games);
} catch (IOException e) {
log.error("[Couldn't write to file] ", e.getMessage());
}
}
在此之后,我的 JSON 看起来像:
{
"Never Alone: Ki Edition" : {
"Title" : "Never Alone: Ki Edition",
"Genre" : "Adventures",
"Price" : "4,99 €",
"Last updated" : "September 15, 2016",
"Current version" : "1.0.0",
"Requirements" : "2.3+",
"IAP" : "nope",
"Contacts" : "support@neveralonegame.com"
},
...
如果我用 lombok @Getter 注释我的班级,就会出现奇怪的字段:
{
"Never Alone: Ki Edition" : {
"iap" : "nope"
"Title" : "Never Alone: Ki Edition",
"Genre" : "Adventures",
"Price" : "4,99 €",
"Last updated" : "September 15, 2016",
"Current version" : "1.0.0",
"Requirements" : "2.3+",
"IAP" : "nope",
"Contacts" : "support@neveralonegame.com"
},
我不明白这个领域:
"iap" : "nope"
杰克逊从哪里找到的?我用日志检查了我的本地地图,一切都很好,这个字段不存在,但在序列化过程中它出现了。
解决方案
我同意user2447161。Lombok 正在尝试为“IAP”创建一个正确的 getter 名称,但 Jackson 和 Lombok 在非标准变量名称应该如何成为 getter 方面存在分歧,因此 Jackson 不知道两个 IAP(变量和 getter)是相同的。重命名你的变量“iap”,一切都会好起来的。