Jackson Java 到 JSON 对象映射器修改字段名称

Jackson Java to JSON object mapper modifies field's name

使用 Jackson 将 Java 对象转换为 JSON

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
jsonMessage = mapper.writeValueAsString(object);

结果是字段"participants"(对象实例的一部分)

participants    Arrays$ArrayList<E> 

重命名为 "participantsList"

participantsList":[{"userId":"c1f9c"}]

即"List" 附加到字段名称。我浏览了 Jackson 文档,但没有找到防止这种情况发生的方法。这可能吗?在独立项目中测试上述代码不会导致相同的结果(即不会发生重命名)。为什么杰克逊会这样?不幸的是,该对象是第三方的,我无法更改它。

使用 Jackson 版本 2.3.3(使用 2.9.0 验证了相同的行为)。

Oleksandr 的评论指出了正确的方向。确实有一个 getParticipantsList() ,杰克逊在确定 JSON 字段名称时似乎考虑到了这一点。但是,正如我之前所写,考虑到它是第三方对象,我无法在那里进行任何更改。

但是,通过更好地了解导致问题的原因,我能够想出一个解决方案:

mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY).withGetterVisibility(Visibility.NONE).withIsGetterVisibility(Visibility.NONE));

mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);

也许您可以使用 USE_ANNOTATIONS 跳过这样的注释:

    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(MapperFeature.USE_ANNOTATIONS, false);
    String jsonMessage = mapper.writeValueAsString(object);