1. Json字符串转化为JSONObject对象 :
String str = "{ \"user\": [\"c00296813\",\"x000001\"]}";
JSONObject jsonObject = JSONObject.fromObject(str);
2. JSONObject转化为json字符串:
String string = jsonObject.toString();
3. JSONObject.toBean(JSONObject , JSONConfig.class) 讲JSONObject转化为JavaBean :
package com.example.demo;
public class people {
private int id;
private int age;
private String name;
public people(int id, int age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
public people() {super(); }
public int getId() {return id; }
public void setId(int id) {this.id = id; }
public int getAge() {return age; }
public void setAge(int age) {this.age = age; }
public String getName() {return name; }
public void setName(String name) {this.name = name; }
@Override
public String toString() {
return "people{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
转化:
// JSONObject.toBean(jsonObject, JSONObject.class);
People people =(People)JSONObject.toBean(jsonObject, people.class);
4. 讲一个集合json转化为List<T>集合:
String jsonpeople = "[{"age":1,"id":1,"name":"first"},
{"age":2,"id":2,"name":"second"},
{"age":3,"id":3,"name":"third"}]" ;
//讲json字符串转化为List<T>集合
String jsonPeople ="[{\"age\":\"1\",\"id\":\"1\",\"name\":\"张三\"}," +
"{\"age\":\"2\",\"id\":\"2\",\"name\":\"李四\"}," +
"{\"age\":\"3\",\"id\":\"3\",\"name\":\"王五\"}]\n" ;
JSONArray jsonArray = JSONArray.fromObject(jsonPeople);
List<People> peopleList = (List<People>) JSONArray.toCollection(jsonArray,People.class);
5. JSONArray的遍历
for(int i= 0;i<jsonArray.size();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
People people = (People)JSONObject.toBean(jsonObject,People.class);
}