-
把它封裝成JSON對象
-
package itcast.cn;
-
-
import org.json.JSONException;
-
import org.json.JSONObject;
-
-
public class Jasonexercise {
-
/*
-
* {
-
"employees": [
-
{ "firstName":"Bill" , "lastName":"Gates" },
-
{ "firstName":"George" , "lastName":"Bush" },
-
{ "firstName":"Thomas" , "lastName":"Carter" }
-
]
-
}
-
-
* */
-
public static void main(String[] args) throws Exception {
-
//最外層只有[]或者{}
-
//其中{}表示對象
-
//[]表示數組
-
//.物件模型
-
//1.建立jason資料,也就是一個對象的資料串
-
String Jason="{‘id‘:‘001‘,‘name‘:‘謝雨‘,‘age‘:‘18‘}";
-
//封裝成一個json對象
-
JSONObject jsonObject = new JSONObject(Jason);
-
String name = jsonObject.getString("name");
-
System.out.println(name);
-
String age = jsonObject.getString("age");
-
System.out.println(age);
-
}
-
-
}
-
把它封裝成JSON數組
-
* */
-
public static void main(String[] args) throws Exception {
-
//[]裡面是數組,裡面放的是兩個對象
-
String ja = "[{‘id‘:‘001‘,‘name‘:‘謝雨‘,‘age‘:‘18‘},{‘id‘:‘001‘,‘name‘:‘老王‘,‘age‘:‘28‘}]";
-
JSONArray jsonArray = new JSONArray(ja);
-
//現在需要拿到老王的話。需要先獲得這個數組的第二個對象
-
JSONObject jsonObject = jsonArray.getJSONObject(1);
-
String name = jsonObject.getString("name");
-
String age = jsonObject.getString("age");
-
System.out.println(name);
-
System.out.println(age);
-
-
-
把它用對象遍曆
-
//其中{}表示對象
-
//[]表示數組
-
//.物件模型
-
//1.建立jason資料,也就是一個對象的資料串
-
String Jason="{‘id‘:‘001‘,‘name‘:‘謝雨‘,‘age‘:‘18‘}";
-
//封裝成一個json對象
-
JSONObject jsonObject = new JSONObject(Jason);
-
//這裡是拿到所有的keys
-
Iterator iterator = jsonObject.keys();
-
//遍曆這個迭代器
-
while (iterator.hasNext()) {
-
String key=(String)iterator.next();
-
//通過key取值
-
String value = jsonObject.getString(key);
-
System.out.println(key+"="+value);
-
-
}
-
把它用數組遍曆
-
//[]裡面是數組,裡面放的是兩個對象
-
String ja = "[{‘id‘:‘001‘,‘name‘:‘謝雨‘,‘age‘:‘18‘},{‘id‘:‘002‘,‘name‘:‘老王‘,‘age‘:‘28‘}]";
-
JSONArray jsonArray = new JSONArray(ja);
-
for (int i = 0; i < jsonArray.length(); i++) {
-
JSONObject jsonObject = jsonArray.getJSONObject(i);
-
Iterator iterator = jsonObject.keys();
-
while (iterator.hasNext()) {
-
String key = (String) iterator.next();
-
String value = jsonObject.getString(key);
-
System.out.println(key+"="+value);
-
}
-
}