JSON数据解析
JSON:JavaScript Object Notation
JSON数据是一系列键值对的集合。
JSON是一种轻量级的数据交换格式,易于阅读和编写,同时也易于机器解析和生成。
JSONObject
JSONArray
JSON:JavaScript Object Notation
JSON数据是一系列键值对的集合。
JSON是一种轻量级的数据交换格式,易于阅读和编写,同时也易于机器解析和生成。
JSON格式是属性,值对的集合。一个对象的开始于“{”,结束于“}”。每一个属性名和值间用“:”提示,属性间用“,”分隔。
JSONObject
JSONArray
GSON:GSON是Google提供的用来在JAVA对象和JSON数据之间进行映射的java类库,可以将一个JSON字符转成一个Java对象,或者反过来。
案例
private String jsonString="[{\"empNo\":\"jredu001\"," +
"\"empName\":\"jereh\"," +
"\"address\":{\"city\":\"yantai\"}}]";
List<Employee> emps=new ArrayList<Employee>();
JSONArray jsonArray=new JSONArray(jsonString);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String empNo=jsonObject.getString("empNo");
String empName=jsonObject.getString("empName");
JSONObject addjsonObject= jsonObject.getJSONObject("address");
String cityString=addjsonObject.getString("city");
Employee employee=new Employee();
employee.setEmpNO(empNo);
employee.setEmpName(empName);
employee.setCity(cityString);
emps.add(employee);
}
public class Employee {
private String empNO;
private String empName;
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEmpNO() {
return empNO;
}
public void setEmpNO(String empNO) {
this.empNO = empNO;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Employee(String empNO, String empName) {
super();
this.empNO = empNO;
this.empName = empName;
}
public Employee() {
super();
}
}