Search code examples
javajsonserializationjacksondeserialization

Is there a Jackson annotation to use a wrapper class during deserialization as well as during serialization for Strings


Hi StackOverflow Community,

I am currently trying to deserialize JSON request bodies provided via Spring Boot @RestController.

The request body contains the following array:

{
  ...
  "productIds": [
    "123abc",
    "234def"
  ],
  ...
}

However, I don't want to deserialize the product IDs into a list of Strings, but rather use a simple wrapper class (for various reasons, including but not limited to additional type safety and validation opportunities). Consequently the class looks like this (Lombok annotations were used to keep the code snippet short):

@Value
@AllArgsConstructor
public class TheRequest {
   ...
   List<ProductId> productIds;
   ...
}

with ProductId being just a simple wrapper as already said (validation annotations are omitted for the sake of brevity):

@Value
@AllArgsConstructor
public class ProductId{
   String id;
}

Looking at Stackoverflow I only found ways to achieve this using rather verbose custom deserialization methods. However, I am a bit astonished, that Jackson does not provide this functionality out of the box. Consequently it would be great if anyone has any idea if

  • there is a more elegant way to achieve deserialization of a array of Strings into a List of WrapperObjects, ideally only using Jackson annotations?
  • there is an elegant way to achieve serialization of such a resulting List of ProductId wrapper objects back into String objects, ideally also using only Jackson annotations? I tried Jacksons @Value but that did not provide the required result.

Solution

  • To me still to verbose but it seems to be a working solution with Jacson 2.14+:

    public record PayloadId(String id) {
    
      @JsonCreator(mode = Mode.DELEGATING)
      public PayloadId{}
    
      @JsonValue
      @Override
      public String id() {
        return id;
      }
    }
    

    ...and here is the records test https://github.com/FasterXML/jackson-databind/blob/2.14/src/test-jdk14/java/com/fasterxml/jackson/databind/records/RecordCreatorsTest.java