Search code examples
javajsonjackson

Json array map position to java property with jackson


Is there a way in Jackson to map json array's positions to different class properties?

For example if we have an api that returns person properties as array (0 is the id, 1 is the name,2 is the age, etc.) how to map this to an object that has properties id, name and age?

"person": [
1,
"Evgeni",
35
]


record Person(Long id, String name, Integer age)

Looking for something like:

@JsonProperty("<get the item at position 1>") String name

Solution

  • You can create a custom deserializer using the JsonDeserializer interface and map the contents of a JSON array to the corresponding properties by overriding the class deserialize(JsonParser p, DeserializationContext ctxt).

    Create a custom deserializer:

    public class FooBarDeserializer extends JsonDeserializer<FooBar> {
    @Override
    public FooBar deserialize(JsonParser p, DeserializationContext ctxt) 
            throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);
        int foo = node.get(0).asInt();
        String bar = node.get(1).asText();
    
        return new FooBar(foo, bar);
      }
    }
    

    Annotate the class with the custom deserializer:

    @JsonDeserialize(using = FooBarDeserializer.class)
    public class FooBar {
      private int foo;
      private String bar;
    }
    

    Deserialize the JSON:

    public static void main(String[] args) throws Exception {
      String json = "[42, \"hello\"]";
    
      ObjectMapper mapper = new ObjectMapper();
      FooBar fooBar = mapper.readValue(json, FooBar.class);
    
      ...
    }