json 构造与解析

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();
		}

	}

}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。