我有一个JavaBean:
public Class Account{
String userName;
String id;
List<Detail> details;
class Detail{
String num;
String name;
}
}
有JSON:
{"username":"Tony","id":"123","details":[{"num":"1","name":"Tom"},{"num":"2","name":"Jerry"}]}
如何使用Jackson进行反序列化?感谢
答案 0 :(得分:2)
首先,userName
字段名称应与json String(用户名)中的相同。
将List<Destail>
至List<Detail>
和detail
班级名称的拼写错误修正为Detail
。
为类字段添加getter和setter。
使用以下示例反序列化json:
String jsonStr = "{\"userName\":\"Tony\",\"id\":\"123\",\"details\":[{\"num\":\"1\",\"name\":\"Tom\"},{\"num\":\"2\",\"name\":\"Jerry\"}]}";
ObjectMapper mapper = new ObjectMapper();
try {
Account account = mapper.readValue(jsonStr, Account.class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}