Using Jackson to convert a Java object to JSON
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
jsonMessage = mapper.writeValueAsString(object);
the result is that the field "participants" (which is part of the object instance)
participants Arrays$ArrayList<E>
gets renamed to "participantsList"
participantsList":[{"userId":"c1f9c"}]
i.e. "List" is appended to the field name. I went through the Jackson documentation but haven't found a way to prevent this from happening. Is this possible? Testing the above code in a standalone project does not cause the same result (i.e. no renaming takes place). Why is Jackson behaving like this? Unfortunately, the object is third party and I cannot change it.
Using Jackson version 2.3.3 (same behaviour verified with 2.9.0).
答案 0 :(得分:4)
Oleksandr的评论指出了正确的方向。确实,杰克逊在确定JSON字段名称时似乎考虑了一个getParticipantsList()。但是,正如我之前所写,我无法在那里进行任何更改,因为它是第三方对象。
但是,通过更好地了解导致问题的原因,我能够找到解决方案:
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);
答案 1 :(得分:-1)
也许您可以使用USE_ANNOTATIONS跳过这样的注释:
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(MapperFeature.USE_ANNOTATIONS, false);
String jsonMessage = mapper.writeValueAsString(object);