1、maven依赖
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.50</version>
</dependency>
</dependencies>
2、常用方法
将json字符串转换成javaBean
public static void json2Bean(){
String jsonStr = "{\"id\":1001,\"name\":\"Jobs\"}";
User user = JSONObject.parseObject(jsonStr, User.class);
}
将json字符串数组转换成List集合
public static void json2ListBean1() {
String jsonStr = "[{\"id\":1001,\"name\":\"Jobs\"},{\"id\":1002,\"name\":\"jack\"}]";
List<User> users = JSONObject.parseArray(jsonStr, User.class);
}
public static void json2ListBean(){
String jsonStr = "[{\"id\":1001,\"name\":\"Jobs\"},{\"id\":1002,\"name\":\"jack\"}]";
List<User> list1 = JSONObject.parseObject(jsonStr, new TypeReference<List<User>>() {});
将javaBean转换成json对象
public static void bean2Json(){
String tom = JSONObject.toJSONString(new User(1000, "tom"));
System.out.println(tom);
}
3、获取复杂json中的值(一般用于调用第三方的接口)
json:[
{
person:{
name:"蔡徐坤",
age:20
}
},
{
person:{
name:"乔碧萝",
age:50
}
}
]
JSONArray array = JSONArray.fromObject(json);
for(int i = 0;i < array.size();i++){
JSONObject obj = JSONObject.fromObject(array.get(i));
String name = obj.getJSONObject("person").get("name").toString();
}