假设现在要创建这样一个json文本
{
"phone" : ["123231", "1231234"], // 数组
"name" : "chenyisheng", // 字符串
"age" : 22, // 数值
"address" : { "country" : "china", "province" : "guangzhou" }, // 对象
"married" : false // 布尔值
使用JSONObject JSONArray构建 Json文本
{
"phone" : ["123231", "1231234"], // 数组
"name" : "chenyisheng", // 字符串
"age" : 22, // 数值
"address" : { "country" : "china", "province" : "guangzhou" }, // 对象
"married" : false // 布尔值
}
使用JSONObject JSONArray构建 Json文本
try {
JSONObject people = new JSONObject(); //{ }新建people对象
JSONArray phone = new JSONArray(); //phone是个数组
phone.put("123231").put("1231234"); //把电话号码放到phone里面
people.put("phone", phone); //把phone放到people里面
people.put("name", "chenyisheng"); //把name放到people里面
people.put("age", 22); //把age放到people里面
JSONObject address = new JSONObject(); //address是对象 所以new JSONObject
address.put("country", "china"); //把coutry放到address里面
address.put("province", "guangzhou"); //把province放到address里面
people.put("address", address); //把整理好的address放到people里面
people.put("married", false); //把married放到people里面
} catch (JSONException e) {
// TODO: handle exception
throw new RuntimeException(e); //抛异常
}
使用JSONStringer构建Json文本
try {
JSONStringer jsonText = new JSONStringer();
jsonText.object(); // { 对象开始
jsonText.key("phone"); // phone数组
jsonText.array(); // [ 符号开始
jsonText.value("123231"); // 数值123231
jsonText.value("1231234"); // 数值1231234
jsonText.endArray(); // ] 符号结束
jsonText.key("name"); // name属性
jsonText.value("chenyisheng"); // name数值
jsonText.key("age"); // age属性
jsonText.value(22); // age数值
jsonText.key("address"); // address对象
jsonText.object(); // { 符号开始
jsonText.key("country"); // country属性
jsonText.value("china"); // country数值
jsonText.key("province"); // province属性
jsonText.value("guangzhou"); // province数值
jsonText.endObject(); // } 符号结束
jsonText.key("married"); // married 属性
jsonText.value(false); // married 数值
jsonText.endObject(); // } 对象结束
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException(e); //抛异常
}
解析JSON文本
try {
JSONObject json = new JSONObject(jsonText);
JSONArray phone = json.getJSONArray("phone");
String[] phones = {""} ;
for(int index = 0; index < phone.length(); index++){
phones[index] = phone.getString(index);
}
String name = json.getString("name");
int age = json.getInt("age");
JSONObject address = json.getJSONObject(address);
String country = address.getString("country");
String province = address.getString("province");
Boolean married = json.getBoolean("married");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}