javajsonjakarta-eejsonb-api

Deserializing JSON array with JSON-B


I'm trying to deserialize a JSON Array with JSONB.

JSON

[
  {
    "id": "1",
    "animal": "dog",
    "age": "3"
  },
  {
    "id": "2",
    "animal": "cat",
    "age": "5"
  }
]

Controller

Jsonb jsonb = JsonbBuilder.create();    
Animal animal;
AnimalsList animalsList;

public AnimalsList getAnimals() {
    try {
        animalsList = jsonb.fromJson("[{\"id\":\"1\",\"animal\":\"dog\",\"age\":\"3\"},{\"id\":\"2\",\"animal\":\"cat\",\"age\":\"5\"}]", AnimalsList.class);
    } catch (JSONException ex) {
        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
    }
    return animalsList;
}

AnimalsList

public class AnimalsList implements Serializable{

    private List<Animal> list;

    public AnimalsList() {
    }

    public AnimalsList(List<Animal> list) {
        this.list = list;
    }

    // getter & setter
}

Animal

public class Animal implements Serializable{

    private int id;
    private String animal;
    private int age;

    public Animal() {
    }

    public Animal(int id, String animal, int age) {
        this.id = id;
        this.animal = animal;
        this.age = age;
    }

    // getter & setter
}

But I get the following error:

javax.json.bind.JsonbException: Can't deserialize JSON array into: class com.model.AnimalsList

Solution

  • As written in the comment of Arnaud, this guide shows a solution:

    List<Dog> dogs = new ArrayList<>();
    dogs.add(falco);
    dogs.add(cassidy);
    
    // Create Jsonb and serialize
    Jsonb jsonb = JsonbBuilder.create();
    String result = jsonb.toJson(dogs);
    
    // Deserialize back
    dogs = jsonb.fromJson(result, new ArrayList<Dog>(){}.getClass().getGenericSuperclass());