JSON (JavaScript 对象表示法)
1.名称值对
名称可以使用双引号,单引号,也可以不写
值
数字(整数或浮点数)
字符串(在双引号中)字符串必须 写 双引号或单引号
逻辑值(true 或 false)
数组(在方括号中)
对象(在花括号中)
null
2.JSON两种结构
对象 {key:value,key:value,….}
数组 [‘aaa’,’bbb’,’ccc’]
3.java中解析JSON
三种方式
官方jar
gson
fast-json
用三种方法解析 {no:1,name:’android部门’,employees:[{name:’张三’,age:20},{name:’李四’,age:18},{name:’王五’,age:21}]}
public class JsonParseDemo3 {
public static void main(String[] args) throws Exception {
//
String json = "{no:1,name:'android部门',employees:[{name:'张三',age:20},{name:'李四',age:18},{name:'王五',age:21}]}";
json(json);
gson(json);
fastjson(json);
}
// 官方
public static void json(String json) throws Exception {
JSONObject jsonObject=new JSONObject(json);
int no=jsonObject.getInt("no");
String name=jsonObject.getString("name");
JSONArray jsonArray=jsonObject.getJSONArray("employees");
ArrayList<Employee> employees=new ArrayList<Employee>();
//遍历数组
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj= jsonArray.getJSONObject(i);
Employee employee=new Employee();
employee.setName(obj.getString("name"));
employee.setAge(obj.getInt("age"));
employees.add(employee);
}
Dept dept=new Dept(no,name,employees);
dept.showInfo();
}
// 谷歌 Gson
public static void gson(String json) {
Gson gson=new Gson();
Dept dept=gson.fromJson(json, Dept.class);
dept.showInfo();
}
// 阿里巴巴 fastjson
public static void fastjson(String json) {
Dept dept=JSON.parseObject(json, Dept.class);
dept.showInfo();
}
}