javajackson-databind

How do I use jackson to map json with double Array to a custom Object


I have a .json file that contains string to double array value. Currently I can get a Map<String, List<List<Double>>> which works but, I would like to get a Map<String, List<MyPoint>> back instead.

  static String JSON = """
      {
        "data1": [ [ 1, 2, 3], [4, 5, 6] ],
        "data2": [ [ 9, 8, 7], [6, 5, 4] ]
      }
      """;

    public static void main(String[] args){
        ObjectMapper mapper = new ObjectMapper();
        Map<String, List<List<Double>>> values = mapper.readValue(JSON, Map.class);
    }

How could I set this up so that instead of a List<List<Double>> I could have a List<MyPoint> instead? How do I convert a List<Double> to MyPoint. MyPoint is a class I can design for this conversion.

This is similar to How to use Jackson to deserialise an array of objects but I need to include a conversion.


Solution

  • One way to do this is to use a StandarConverter that converts a List to MyPoint and it required adding an annotation @JsonDeserialize(converter = MyPointConverter.class) to indicate which converter gets used.

    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
    import com.fasterxml.jackson.databind.util.StdConverter;
    ​
    import java.util.List;
    import java.util.Map;
    ​
    public class Test {
      static String JSON = """
          {
            "data1": [ [ 1, 2, 3], [4, 5, 6] ],
            "data2": [ [ 9, 8, 7], [6, 5, 4] ]
          }
          """;
    ​
      public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, List<MyPoint>> data = mapper.readValue(JSON, new TypeReference<>() {});
        System.out.println(data);
      }
    ​
      @JsonDeserialize(converter = MyPointConverter.class)
      record MyPoint(List<Double> data) {
      }
    ​
      static class MyPointConverter extends StdConverter<List<Double>, MyPoint> {
        @Override
        public MyPoint convert(List<Double> value) {
          return new MyPoint(value);
        }
      }
    }