第一种方法
1
2
3
4
5
6
7
8
9
String jsonStr = "[{\"id\": \"0\", \"ip\": \"123\", \"mac\": \"456\"},
{\"id\": \"1\", \"ip\": \"111\", \"mac\": \"222\"}]";
List<User> userList = new ArrayList<User>();
ObjectMapper mapper = new ObjectMapper();
// 避免JSON里面包含了实体没有的字段导致反序列化失败
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 转为对象数组
userList = mapper.readValue(jsonStr,
mapper.getTypeFactory().constructCollectionType(List.class, User.class));
第二种方法
1
2
3
4
5
6
7
8
9
10
11
12
String jsonStr = "[{\"id\": \"0\", \"ip\": \"123\", \"mac\": \"456\"},
{\"id\": \"1\", \"ip\": \"111\", \"mac\": \"222\"}]";
List<User> userList = new ArrayList<User>();
JSONArray jsonArray = JSONArray.parseArray(jsonStr);
for (int i = 0; i < jsonArray.size(); i++) {
User user = new User();
JSONObject object = (JSONObject) jsonArray.get(i);
user.setId(object.get("id"));
user.setIp(object.get("ip"));
user.setMac(object.get("mac"));
userList.add(user);
}