javajsonjsonbyasson

How to parse array of numeric values in a JSON to Java object with Jsonb


I love how easy it is to map JSON data to a Java object with Jsonb, but I seem to have stumbled upon a not well-documented use-case...

Given this json data:

{
  "id": "test",
  "points": [
    [
      -24.787439346313477,
      5.5551919937133789
    ],
    [
      -23.788913726806641,
      6.7245755195617676
    ],
    [
      -22.257251739501953,
      7.2461895942687988
    ]
  ]
}

What can be used as the object type to store the points-values?

import jakarta.json.bind.annotation.JsonbProperty;

public class Temp {

    @JsonbProperty("id")
    private String id;
        
    @JsonbProperty("points")
    private ??? points;

    // Getters-Setters
}

So I can create the Temp-object with:

import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;
    
Jsonb jsonb = JsonbBuilder.create();
Temp temp = jsonb.fromJson(jsonString, Temp.class);

So far I've tried the following:


Solution

  • Let's try it:

    @Data
    public class Temp {
        @JsonbProperty("id")
        private String id;
        
        @JsonbProperty("points")
        private List<List<BigDecimal>> points;
        
        public static void main(String[] args) {
            String jsonString = "{\n" +
                                "  \"id\": \"test\",\n" +
                                "  \"points\": [\n" +
                                "    [\n" +
                                "      -24.787439346313477,\n" +
                                "      5.5551919937133789\n" +
                                "    ],\n" +
                                "    [\n" +
                                "      -23.788913726806641,\n" +
                                "      6.7245755195617676\n" +
                                "    ],\n" +
                                "    [\n" +
                                "      -22.257251739501953,\n" +
                                "      7.2461895942687988\n" +
                                "    ]\n" +
                                "  ]\n" +
                                "}";
            Jsonb jsonb = JsonbBuilder.create();
            Temp temp = jsonb.fromJson(jsonString, Temp.class);
            System.out.println(temp);
        }
    }