码迷,mamicode.com
首页 > Web开发 > 详细

json 构造与解析

时间:2015-03-30 01:22:43      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.JsonObject;

public class Test {
	public static void main(String[] args) {
		String s;
		try {
			/*
			 * 构造json 数据
			 * {"In":10,"Nums":[123,456,789],"Boolean":false,"Strings":
			 * {"Str2":"MyStr2","Str1":"MyStr1"}}
			 */
			JSONObject jsonObject = new JSONObject();
			JSONObject strs = new JSONObject();
			strs.put("Str1", "MyStr1");
			strs.put("Str2", "MyStr2");
			jsonObject.put("Strings", strs);

			JSONArray jsonArray = new JSONArray();
			jsonArray.put(123).put(456).put(789);
			jsonObject.put("Nums", jsonArray);

			jsonObject.put("In", 10);

			jsonObject.put("Boolean", false);
			s = jsonObject.toString();
			System.out.println(jsonObject.toString());

			Test test = new Test();
			test.parserJson(s);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * {"In":10,
	 * "Nums":[123,456,789],
	 * "Boolean":false,
	 * "Strings":{"Str2":"MyStr2","Str1":"MyStr1"}}
	 */
	private void parserJson(String jsonStr) {
		try {
			JSONObject jsonObject = new JSONObject(jsonStr);
			// 单个数据解析
			System.out.println("In = " + jsonObject.getString("In"));
			System.out.println("Boolean = " + jsonObject.getString("Boolean"));
			// 多个数据解析
			String jsonChildStr = jsonObject.getString("Strings");
			JSONObject objectStrs = new JSONObject(jsonChildStr);
			String str1 = objectStrs.getString("Str1");
			String str2 = objectStrs.getString("Str2");
			System.out.println("Str1 = " + str1);
			System.out.println("Str1 = " + str2);
			// 解析jsonArrary
			JSONArray jsonArray =jsonObject.getJSONArray("Nums");
			for (int i = 0; i < jsonArray.length(); i++) {
				System.out.println(jsonArray.get(i));
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

 

json 构造与解析

标签:

原文地址:http://www.cnblogs.com/maliu/p/4376868.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!