Ramon De Les Olives
Ramon De Les Olives

Reputation: 667

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

Upvotes: 2

Views: 591

Answers (2)

senerh
senerh

Reputation: 1365

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));

Upvotes: 1

Nu&#241;ito Calzada
Nu&#241;ito Calzada

Reputation: 2056

Type listType = new TypeToken<List<Show>>() {}.getType();
return mapper.readValue(jsonStr, listType.class);

Upvotes: 0

Related Questions