1.Gson
1.1把对象转换为json字符串
Gson gson = new Gson();
String userJson = gson.toJson(userObject);
1.2 把json字符串转换为对象
// str代表的是json字符串,Student.class代表的是你要转成的类型
Gson gson = new Gson();
Student student = gson.fromJson(str, Student.class);
1.3 把json字符串转换为List对象
Type type = new TypeToken<List<User>>() {
}.getType();
List<User> userLists = new Gson().fromJson(json, type);
1.4 把list转换为json格式字符串
String json = new Gson().toJson(list);
2.Jackson
2.1 把对象转换为json字符串
ObjectMapper objectMapper = new ObjectMapper();
People peo = new People();
String jsonStr = objectMapper.writeValueAsString(peo);
2.2 把json字符串转换为对象
ObjectMapper objectMapper = new ObjectMapper();
People peo = objectMapper.readValue(jsonStr, People.class);
2.3 把json字符串转换为List集合
ObjectMapper objectMapper = new ObjectMapper();
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, People.class);
List<People> list = objectMapper.readValue(jsonStr, javaType);