Search code examples
javajsonjacksonjackson2

Parsing Json file with Jackson


I call a WS that returns a Json object like follows:

   {
        "id": "salton", 
        "name": "salton", 
    }

which I parse without any problem using

ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jsonStr, Show.class);

Then I have another WS that return a list of objects, as follows

{
    "id": "saltonId", 
    "name": "salton", 
},
{
    "id": "elCordeLaCiutat", 
    "name": "elCordeLaCiutat", 
}

which I want to parse using

ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jsonStr, List<Show.class>.class);

but I got compilation problems

Multiple markers at this line
    - List cannot be resolved to a variable
    - Syntax error on token ">", byte expected after this 
     token

Solution

  • A list of objects should be wrapped in [] as follows

    [
        {
            "id": "saltonId", 
            "name": "salton", 
        },
        {
            "id": "elCordeLaCiutat", 
            "name": "elCordeLaCiutat", 
        }
    ]
    

    which you can unmarchal like that:

    ObjectMapper mapper = new ObjectMapper();
    List<Show> shows = Arrays.asList(mapper.readValue(json, Show[].class));