Json to java object conversion using jackson when the key value is changing

Viewed 205

I am using Jackson to convert the JSONObject to java. Below is my json message format which I am getting from an API.

{"menu": {
    "header": "SVG Viewer",
    "items": [
        {"0": "Open"},
        {"1": "OpenNew", "label": "Open New"},
        null,
        {"2": "ZoomIn", "label": "Zoom In"},
        {"3": "ZoomOut", "label": "Zoom Out"},
        {"4": "OriginalView", "label": "Original View"},
        null,
        {"5": "Quality"},
        {"6": "Pause"},
        {"7": "Mute"},
        null,
        {"8": "Find", "label": "Find..."},
        {"9": "FindAgain", "label": "Find Again"},
        {"10": "Copy"},
        {"11": "CopyAgain", "label": "Copy Again"},
        {"12": "CopySVG", "label": "Copy SVG"},
        {"13": "ViewSVG", "label": "View SVG"},
        {"14": "ViewSource", "label": "View Source"},
        {"15": "SaveAs", "label": "Save As"},
        null,
        {"16": "Help"},
        {"17": "About", "label": "About Adobe CVG Viewer..."}
    ]
}}

Would like to know how can I handle the id key in the message. It is a number from 0 to 17. Using an online converter I get it as below.

public class Item{
    @JsonProperty("0") 
    public String _0;
    @JsonProperty("1") 
    public String _1;
    public String label;
    @JsonProperty("2") 
    public String _2;
    @JsonProperty("3") 
    public String _3;
    @JsonProperty("4") 
    public String _4;
    @JsonProperty("5") 
    public String _5;

would like to know best approach to solve my problem.

1 Answers

Option 1. If you define your data classes like

    public class Base {
        public Menu menu;
    }
    public class Menu {
        public String header;
        public List<Map<String, String>> items;
    }

standard deserialization with Jackson

 Base object = new ObjectMapper().readValue(jsonSrc, Base.class);

will produce object, where every element of items will be a Map containing pairs like <"3","ZoomOut">,"label","Zoom Out">.

Option 2. You can define class Item like

    public class Item {
        public int id;
        public String label;
    }

and implement a custom JsonDeserializer to fill the properties of Item correctly.

Related