Search code examples
javajsonjacksondeserializationobjectmapper

How to deserialize json using objectMapper which has variable key


I have a json file like this. I want to convert this to object of my custom class that has the ID,SYMBOL,COUNT,SYMBOLINDEX as member variable, I cannot directly do it with objectMapper since the keys are varibale "0", "1", "434" they will be integers but are variable. They might also not be in incremental manner for example it can be like "323" then next can be like "5" so how can i convert this to object using objectMapper. Any code suggestions would be highly appreciated

        "0": {
            "symbol": "B",
            "count": 2,
            "symbolIndex": [0, 0]
        },
        "1": {
            "symbol": "B",
            "count": 2,
            "symbolIndex": [0, 0]
        },
        "2": {
            "symbol": "B",
            "count": 2,
            "symbolIndex": [0, 0]
        }
    } ```

Solution

  • You can try something like...

    public static void main(String[] args) {
    
        ObjectMapper map = new ObjectMapper();
        Map convertValue;
        try {
            convertValue = map.readValue(json, Map.class);
            System.out.println(convertValue.values());
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        
    }
    

    You will get result like: [{symbol=B, count=2, symbolIndex=[0, 0]}, {symbol=B, count=2, symbolIndex=[0, 0]}, {symbol=B, count=2, symbolIndex=[0, 0]}]