json字串,JSONObject物件,JavaBean物件互轉。
阿新 • • 發佈:2019-02-13
1.json字串轉為JSONObject物件:
String jsonStr = "{\"name\":\"1\",\"age\":1,\"id\":0}"; // json字串轉為JSONObject 物件 JSONObject jsonObject = JSONObject.fromObject(jsonStr); System.out.println("name:" + jsonObject.get("name")); System.out.println("age:" + jsonObject.get("age")); System.out.println("id:" + jsonObject.get("id"));
2.JSONObject轉為json字串:
// JSONObject轉為json字串
String string = jsonObject.toString();
System.out.println("string" + string);
javaBean物件如下:
package pojo; 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 String getName() { return name; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name; } @Override public String toString() { return "People [id=" + id + ", age=" + age + ", name=" + name + "]"; } }
3.JSONObject物件轉化為javaBean物件:
// JSONObject轉為javaBean
People people = (People)JSONObject.toBean(jsonObject, People.class);
System.out.println(people);
4.javaBean物件轉為 JSONObject物件:
// javaBean轉為JSONObject物件 People javaBean = new People(); javaBean.setAge(100); javaBean.setId(1); javaBean.setName("samllking"); JSONObject peopleJson = JSONObject.fromObject(javaBean); String string2 = peopleJson.toString(); System.out.println("String2 : " + string2);
例如如下的一個json字串:
[{"age":1,"id":1,"name":"first"}, {"age":2,"id":2,"name":"second"}, {"age":3,"id":3,"name":"third"}]這個json字串中包含的資料可以轉化為一個List<People>集合,程式碼如下:
// 將List的Json字串轉化為List<T>集合
String listStr = "[{\"age\":1,\"id\":1,\"name\":\"first\"},{\"age\":2,\"id\":2,\"name\":\"second\"},{\"age\":3,\"id\":3,\"name\":\"third\"}]";
JSONArray jsonArray2 = JSONArray.fromObject(listStr);
List<People> peopleList2 = (List<People>)JSONArray.toCollection(jsonArray2, People.class);
for(People peo : peopleList2)
{
System.out.println(peo);
}
6.JSONArray的遍歷:
List<People> peopleList = new ArrayList<People>();
peopleList.add(new People(1,1,"first"));
peopleList.add(new People(2,2,"second"));
peopleList.add(new People(3,3,"third"));
JSONArray jsonArray = JSONArray.fromObject(peopleList);
// JSONArray的遍歷
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
People people1 = (People)jsonObject.toBean(jsonObject2, People.class);
System.out.println(people1);
}
總結:當然這裡面Json字串轉為javaBean的步驟底層肯定是通過java的反射,用一定的字串匹配規則呼叫javaBean的Getter和Setter方法,
這裡面還有一些坑,以後單獨寫一篇詳解。