Android开发之Json-构建Json文本

原文链接: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();
		}

	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值