使用 JSON-B 反序列化 JSON 数组

Deserializing JSON array with JSON-B

我正在尝试用 JSONB 反序列化一个 JSON 数组。

JSON

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

控制器

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

动物列表

public class AnimalsList implements Serializable{

    private List<Animal> list;

    public AnimalsList() {
    }

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

    // getter & setter
}

动物

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
}

但是我收到以下错误:

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

如果您不仅限于使用 JSON-B,您可以通过 TypeReferencing 使用 ObjectMapper 来完成。

private ObjectMapper objectMapper = new ObjectMapper();
List<Animal> animals = objectMapper.readValue(json , new TypeReference<List<Animal>>(){});

正如 Arnaud, this guide 的评论中所写,显示了一个解决方案:

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