Android 解析json要用到org.json包,所以要先引用
import org.json.*;
一、使用JSONObject,JSONArray构建json文本
// 假设现在要创建这样一个json文本
// {
// "name" : "ttcha.net", // 字符串
// "age" : 28, // 数值
// "address" : { "country" : "china", "province" : "jiangsu" }, // 对象
// "phone" : ["13812341234", "13800001111"], // 数组
// "married" : false // 布尔值
// }
try{
JSONObject person = new JSONObject();
//姓名
person.put("name","ttcha.net");
//年龄
person.put("age",28);
//地址
JSONObject address = new JSONObject();
address.put("country", "china");
address.put("province", "jiansu");
person.put("address", address);
//电话
JSONArray phone = new JSONArray();
phone.put("13812341234").put("13800001111");
person.put("phone", phone);
//婚否
person.put("married", false);
} catch (JSONException ex){
throw new RuntimeException(ex);
}二、使用JSONStringer构建json文本
try{
JSONStringer jsonText = new JSONStringer();
jsonText.object();
//
//姓名
jsonText.key("name");
jsonText.value("ttcha.net");
//年龄
jsonText.key("age");
jsonText.value(28);
//地址
jsonText.key("address");
jsonText.object();
jsonText.key("country");
jsonText.value("china");
jsonText.key("province");
jsonText.value("jiangsu");
jsonText.endObject();
//电话
jsonText.key("phone");
jsonText.array();
jsonText.value("13812341234").value("13800001111");
jsonText.endArray();
//婚否
jsonText.key("married");
jsonText.value(false);
//
jsonText.endObject();
} catch(JSONException ex){
//
}三、json文本解析类JSONTokener
JSONTokener jsonParser = new JSONTokener(JSON);
JSONObject person = (JSONObject)jsonParser.nextValue();
//System.out.println(JSON);
String xxx = person.getString("name");
Toast xx = Toast.makeText(MainActivity.this, xxx, Toast.LENGTH_LONG);
xx.show();