如何在一个领域应用Jackson SerializationFeature?

时间:2015-07-29 09:33:27

标签: java json jackson

鉴于以下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的等效注释,但我找不到。你对杰克逊有这个想法吗?

1 个答案:

答案 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>>();