Jackson unable to map JSON to an Object containing a Map

2.9k views Asked by At

I have a Java POJO like so:

public class Widget {
    private Map<String,Object> params;

    // Getter, setter, ctor, etc...
}

I have a method that currently receives a JSON String, and is attempting to use Jackson's ObjectMapper to map that JSON into a Widget instance:

public Widget fromJSON(String json) {
    ObjectMapper jsonMapper = new ObjectMapper();
    return jsonMapper.readValue(json, Widget.class);
}

Currently the JSON I'm passing in is:

{
    "params": [{
        "acks": "all"
    }, {
        "retries": 0
    }, {
        "batch.size": 16384
    }, {
        "linger.ms": 1
    }, {
        "buffer.memory": 33554432
    }, {
        "key.serializer": "org.apache.kafka.common.serialization.StringSerializer"
    }, {
        "value.serializer": "org.apache.kafka.common.serialization.StringSerializer"
    }]
}

When this runs I get the following exception:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance
    of java.util.LinkedHashMap out of START_ARRAY token

I see this other question addressing a very similar problem, except that question addresses using Jackson to map JSON to a Java Map, not an object (Widget) that contains a Java Map.

I've used http://jsonlint.com to verify that the JSON is valid. So I either need to change the JSON or the code, or possibly both. Any ideas?

2

There are 2 answers

0
Tobías On BEST ANSWER

The JSON is valid, but not for a Map. The value of params is an array, it should be an object like:

{
    "params": {
        "acks": "all",
        "retries": 0,
        "batch.size": 16384,
        "linger.ms": 1,
        "buffer.memory": 33554432,
        "key.serializer": "org.apache.kafka.common.serialization.StringSerializer",
        "value.serializer": "org.apache.kafka.common.serialization.StringSerializer"
    }
}

At Jackson Five Minutes you can find the following relation:

Concrete Java types that Jackson will use for simple data binding are:

╔══════════════════════╦══════════════════════════════╗
║      JSON Type       ║          Java Type           ║
╠══════════════════════╬══════════════════════════════╣
║ object               ║ LinkedHashMap<String,Object> ║
║ array                ║ ArrayList<Object>            ║
║ string               ║ String                       ║
║ number (no fraction) ║ Integer, Long or BigInteger  ║
║ number (fraction)    ║ Double (or BigDecimal)       ║
║ true|false           ║ Boolean                      ║
║ null                 ║ null                         ║
╚══════════════════════╩══════════════════════════════╝
0
cassiomolin On

A List<Map<String, Object>> should do the trick:

public class Widget {

    private List<Map<String, Object>> params;

    // Getter and setters ommited
}