鉴于以下POJO,我想仅在SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED
字段上应用links
。
public class HalRepresentation {
@JsonProperty("_links")
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
private final Map<String, List<Link>> links = new HashMap<String, List<Link>>();
@JsonProperty("_embedded")
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
private final Map<String, Object> embedded = new HashMap<String, Object>();
protected HalRepresentation() {
}
public Map<String, List<Link>> getLinks() {
return links;
}
public Map<String, Object> getEmbedded() {
return embedded;
}
}
我尝试将其序列化如下:
ObjectMapper objectMapper = new ObjectMapper()
.enable(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
try {
outputStream.write(objectMapper.writeValueAsBytes(halRepresentation));
outputStream.flush();
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
但是当我这样做时,展开功能也会应用于embedded
字段。我试图找到WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED
的等效注释,但我找不到。你对杰克逊有这个想法吗?
答案 0 :(得分:0)
如@AlexeyGavrilov所述,似乎不可能:https://stackoverflow.com/a/29133209/1225328。解决方法可能是创建自定义JsonSerializer
:
public class SingleElementCollectionsUnwrapper extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
if (!serializers.getConfig().isEnabled(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED)) {
new ObjectMapper().enable(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED).writeValue(gen, value);
} else {
gen.writeObject(value);
}
}
}
然后,使用links
注释@JsonSerialize
字段:
@JsonProperty("_links")
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@JsonSerialize(using = SingleElementCollectionsUnwrapper.class)
private final Map<String, List<Link>> links = new HashMap<String, List<Link>>();