我正在尝试使用 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
2 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
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());
红颜莎娜
TA贡献1842条经验 获得超12个赞
如果您不限于仅使用 JSON-B,则可以通过 TypeReferencing 使用 ObjectMapper 来完成。
private ObjectMapper objectMapper = new ObjectMapper();
List<Animal> animals = objectMapper.readValue(json , new TypeReference<List<Animal>>(){});
添加回答
举报
0/150
提交
取消