Jackson Serialization: Unwrap collection elements using

Nolequen :

Is there a way to serialize collection and its elements unwrapped?

For example I want to serialize 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);
  }
}

Expected:

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

But actual result is:

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

Nolequen :

Custom serializer might help:

  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();
    }
  }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=139643&siteId=1