DArkO
DArkO

Reputation: 16110

android jackson json object mapper array deserialization

i need help parsing a response with the jackson mapper to a POJO. i have this as a response:

 "data": [{
        "item": {
            "downloaded": false,
            "moderated": false,
            "add": false
        }
    },
    {
        "item": {
            "downloaded": false,
            "moderated": false,
            "add": false }
// more

so how do i bind this one with the mapper to a POJO? here is my class that i am trying but it returns that "item" is not recognized and not allowed to be ignored.

public ArrayList<Item> data =  new ArrayList<Item>();

where item is a public static class Item with constructors and all the fields above with getters and setters.

how do i do this. i cant seem to find anywhere how to read data from an array this way.

Upvotes: 11

Views: 9718

Answers (3)

maziar
maziar

Reputation: 601

JsonNode jsonNode = mapper.readValue(s, JsonNode.class); 
JsonNode userCards = jsonNode.path("data");
List<Item> list = mapper.readValue(userCards.toString(), new TypeReference<List<Item>>(){});

Upvotes: 12

Bane
Bane

Reputation: 1782

Here's my variant of maziar's code.

List<Item> list = mapper.readValue( s, new TypeReference<List<Item>>(){} );

It just eliminates the converting first to a JsonNode and converts instead directly to a List; still works fine, outputting a list of Items.

Upvotes: 2

StaxMan
StaxMan

Reputation: 116512

Your example is missing couple of pieces (esp. definition of Item), to know if your structure is compatible; but in general JSON and Object structures need to match. So, you would at least need something like:

public class DataWrapper {
  public List<Item> data; // or if you prefer, setters+getters
}

and if so, you would bind with:

DataWrapper wrapper = mapper.readValue(json, DataWrapper.class);

and access data as

List<Item> items = wrapper.data;

Upvotes: 8

Related Questions