JSONObject與JSONArray的區別簡述:
區別在於JSONObject是一個{}包裹起來的一個對象(Object),
而JSONArray則是[]包裹起來的一個數組(Array),
說白點就是一個是數組一個是對象或字符串。
例1:
package com.rtt.lltest;java
import java.util.HashMap;
import java.util.Map;json
import org.json.JSONArray;數組
import com.rtt.platform.system.util.JSONUtil;app
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
// Object 類型字符串
String json = "{\"name\":\"reiz\",\"age\":\"32\"}";
JSONObject jsonObj = JSONObject.fromObject(json);
String name = jsonObj.getString("name");
System.out.println(name+"||||||||||||||");
// 結果:reiz
jsonObj.put("initial", name.substring(0, 1).toUpperCase());
// jsonObject 添加數組
String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" };
jsonObj.put("likes", likes);
// jsonObject 添加Map
Map<String, String> ingredients = new HashMap<String, String>();
ingredients.put("apples", "3kg");
ingredients.put("sugar", "1kg");
ingredients.put("pastry", "2.4kg");
ingredients.put("bestEaten", "outdoors");
jsonObj.put("ingredients",ingredients);
System.out.println(jsonObj);
System.out.println(jsonObj.getString("likes"));
System.out.println(jsonObj.getString("ingredients"));
org.json.JSONObject jsonObje = new org.json.JSONObject();
JSONUtil.put(jsonObje, "perNum", "lisi");
JSONUtil.put(jsonObje, "cardNum", "12345600");
org.json.JSONObject jsonObjee = new org.json.JSONObject();
JSONUtil.put(jsonObjee, "perNum", "lilei");
JSONUtil.put(jsonObjee, "cardNum", "123456");
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObje);
jsonArray.put(jsonObjee);
System.out.println("---------------------------------");
System.out.println(jsonArray.toString());
}
}spa
=========================================================orm
JSONUtil.java對象
public static void put(JSONObject jsonObj, String key, Object value) {ip
if (value == null) {element
jsonObj.put(key, StringPool.BLANK);字符串
}
else {
jsonObj.put(key, value.toString());
}
}
例2:JSONArray和JSONObject互相添加
package com.rtt.lltest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class ObjTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
JSONObject jo = new JSONObject();
jo.put("isleaf", true);
jo.put("name", "zhangsan");
jo.put("age", "25");
JSONObject jo2 = new JSONObject();
jo2.put("isleaf", false);
jo2.put("name", "lisi");
jo2.put("age", "25");
JSONObject jo3 = new JSONObject();
jo3.put("isleaf", true);
jo3.put("name", "lisi");
jo3.put("age", "25");
JSONArray ja0 = new JSONArray();
//把JSONObject添加到中JSONArray
ja0.add(jo3);
//把JSONArray添加到JSONObject中
jo2.element("children", ja0);
System.out.println(jo2.toString());
JSONArray ja1 = new JSONArray();
ja1.add(jo);
ja1.add(jo2);
ja1.add(jo3);
System.out.println("===================================+++++++++++++++++++++");
System.out.println(ja1.toString());
System.out.println("===================================+++++++++++++++++++++");
}
}