How to serialize single-valued @Data object using Jackson without nesting (e.g. {"id":123}, not {"id":{"value":123}})?
I created an interface which has getValue()
which annotated as @JsonValue
:
public interface LongValue { @JsonValue long getValue();}
Then implemented it in every @Data
classes. note that actual implementation of getValue()
will be automatically generated by Lombok:
@Datapublic final class SomeId implements LongValue, Serializable { private final long value;}
With that I've got the test SomeDTOTest
passed - SomeDTO
is serialized to {"id":123}
as I expected.
You can write custom Serializer for this class.
E.g.:
class CustomSerializer extends StdSerializer<SomeId>{ protected CustomSerializer(Class<SomeId> t) { super(t); } @Override public void serialize(SomeId someId, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { gen.writeNumber(someId.getValue()); } }
Now use this serializer to serialize SomeId
class:
ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(new CustomSerializer(SomeId.class)); mapper.registerModule(module); SomeDTO dto = new SomeDTO(); dto.id = new SomeId(123); String serialized = mapper.writeValueAsString(dto); System.out.println(serialized); // output : {"id":123}