Jackson Serialization:使用展开集合元素

Nol*_*uen 5 java serialization json jackson

有没有办法序列化集合及其展开的元素?

例如,我想序列化 unwrapped all components

class Model {

  @JsonProperty
  @JsonUnwrapped
  Collection<Object> components;

  Model(Collection<Object> components) {
    this.components = components;
  }

  static class Component1 {
    @JsonProperty
    String stringValue;

    Component1(String stringValue) {
      this.stringValue= stringValue;
    }
  }

  static class Component2 {
    @JsonProperty
    int intValue;

    Component2(int intValue) {
      this.intValue= intValue;
    }
  }

  public static void main(String[] args) throws JsonProcessingException {
    Model model = new Model(Arrays.asList(new Component1("something"), new Component2(42)));
    String json = new ObjectMapper().writeValueAsString(model);
    System.out.println(json);
  }
}
Run Code Online (Sandbox Code Playgroud)

预期的:

{"stringValue":"something","intValue":42}

但实际结果是:

{"components":[{"stringValue":"something"},{"intValue":42}]}

Nol*_*uen 3

自定义序列化器可能会有所帮助:

  class ModelSerializer extends JsonSerializer<Model> {

    @Override
    public void serialize(Model model, JsonGenerator generator, SerializerProvider serializers) throws IOException {
      generator.writeStartObject();

      JsonSerializer<Object> componentSerializer = serializers.findValueSerializer(getClass());
      JsonSerializer<Object> unwrappingSerializer = componentSerializer.unwrappingSerializer(NameTransformer.NOP);
      unwrappingSerializer.serialize(this, generator, serializers);

      generator.writeEndObject();
    }
  }
Run Code Online (Sandbox Code Playgroud)