原文链接:http://blog.csdn.net/hudashi/article/details/8736048
先上图:
布局文件:
核心代码:
public class JsonDemoActivity extends Activity {
private Button bt_create_json;
private EditText et_create_json;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt_create_json = (Button) findViewById(R.id.bt_create_json);
et_create_json = (EditText) findViewById(R.id.et_create_json);
bt_create_json.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// createJsonByObject();
createJsonByStringer();
}
});
}
/*
* 假设现在要创建这样一个json文本 { "phone" : ["12345678", "87654321","02887188812"],
* "name" : "yuanzhifei89", "age" : 100, "address" : { "country" : "china",
* "province" : "jiangsu" }, "married" : false }
*/
// 1,使用JSONObject与JSONArray来构建json文本
private void createJsonByObject() {
try {
JSONObject person = new JSONObject();
// 电话是一个数组,用JSONArray
JSONArray phone = new JSONArray();
phone.put("12345678").put("87654321").put("02887188812");
person.put("phone", phone);
person.put("name", "yuanzhifei89");
person.put("age", 100);
// address是一个对象,用JSONObject
JSONObject address = new JSONObject();
address.put("country", "china");
address.put("province", "jiangsu");
person.put("address", address);
person.put("married", false);
et_create_json.setText(person.toString());
} catch (Exception e) {
throw new RuntimeException();
}
}
// 2,使用JsonStringer来构建json文本
private void createJsonByStringer() {
try {
JSONStringer jsonText = new JSONStringer();
/* 首先是{,对象开始。object和endObject必须配对使用 */
jsonText.object();
jsonText.key("phone");
/* 键phone的值是数组。array和endArray必须配对使用 */
jsonText.array();
jsonText.value("12345678").value("87654321");
jsonText.value("02887188812");
jsonText.endArray();
jsonText.key("name");
jsonText.value("yuanzhifei89");
jsonText.key("age");
jsonText.value(100);
jsonText.key("address");
/* 键address的值是对象 */
jsonText.object();
jsonText.key("country");
jsonText.value("china");
jsonText.key("province");
jsonText.value("jiangsu");
jsonText.endObject();
jsonText.key("married");
jsonText.value(false);
/* },对象结束 */
jsonText.endObject();
et_create_json.setText(jsonText.toString());
} catch (Exception e) {
throw new RuntimeException();
}
}
}