Search code examples
javarestjacksonjson-deserialization

Jackson json deserialization with integer(primitive data) as the key into POJO


In one of the APIs, I'm receiving this as the Json response: You can check this response sample here Sample Json resopnse

{
    "histogram" : {
        "1" : "12",
        "2" : "20",
        "3" : "50",
        "4" : "90",
        "5" : "10"
     }
}

In order to deserialize this response, How does one even write the POJO classes ?

In java, since we are not allowed to have numbers as the variable names, how does one convert this into a POJO?

For instance, how can I create something like this:

public class MyPOJO {
    Histogram histogram;

    public static class Histogram {
        // I KNOW THIS IS WRONG !!
        String 1;
        String 2;
        String 3;
        String 4;
    }
}

Does jackson provide any annotations to handle these?


Solution

  • For this JSON:

    {
      "histogram": {
        "1": "12",
        "2": "20",
        "3": "50",
        "4": "90",
        "5": "10"
      }
    }
    

    You can consider one of the the following approaches:

    Using a Map<String, String> to hold the values

    The histogram can the parsed into a Map<String, String>:

    public class HistogramWrapper {
    
        @JsonProperty("histogram")
        private Map<String, String> histogram;
    
        // Getters and setters omitted
    }
    

    Using attributes annotated with @JsonProperty

    Alternatively, you can define a Histogram class and annotate its attributes with @JsonProperty:

    public class HistogramWrapper {
    
        @JsonProperty("histogram")
        private Histogram histogram;
    
        // Getters and setters omitted
    }
    
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Histogram {
    
        @JsonProperty("1")
        private String _1;
    
        @JsonProperty("2")
        private String _2;
    
        @JsonProperty("3")
        private String _3;
    
        @JsonProperty("4")
        private String _4;
    
        @JsonProperty("5")
        private String _5;
    
        // Getters and setters omitted
    }
    

    Parsing the JSON

    To parse the JSON, do as following:

    ObjectMapper mapper = new ObjectMapper();
    String json = "{\"histogram\":{\"1\":\"12\",\"2\":\"20\","
                + "\"3\":\"50\",\"4\":\"90\",\"5\":\"10\"}}";
    
    HistogramWrapper wrapper = mapper.readValue(json, HistogramWrapper.class);