json json数组,json字符串解析

1.
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

public class DateJsonValueProcessor {
	public static void main(String[] args) {
		try {
			String result = "{'id':{'a':'0','b':'1'},'users':[{'toid':1,'tosex':2,'realname':'zs'},{'toid':44,'tosex':55,'realname':'zs'}]}";

			JSONObject json = new JSONObject(result);
			System.out.println("取id值:" + json.get("id"));
			System.out.println("取id中a值:" + json.getJSONObject("id").get("a"));
			System.out.println("取id中b值:" + json.getJSONObject("id").get("b"));
			JSONArray jsonArray = json.getJSONArray("users");
			int iSize = jsonArray.length();
			System.out.println("json中数组Size:" + iSize);
			for (int i = 0; i < iSize; i++) {
				JSONObject jsonObj = jsonArray.getJSONObject(i);
				System.out.println("[" + i + "]toid=" + jsonObj.get("toid"));
				System.out.println("[" + i + "]tosex=" + jsonObj.get("tosex"));
				System.out.println();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}


输出:
取id值:{"a":"0","b":"1"}
取id中a值:0
取id中b值:1
json中数组Size:2
[0]toid=1
[0]tosex=2

[1]toid=44
[1]tosex=55

2.
import org.codehaus.jettison.json.JSONObject;

public class json2 {
	public static void main(String[] args) throws Exception {
		String result = "{'error':{'code':'0','info':'错误由未知错误引起'},'loginStr':{'userid':'12345','name':'黑色头发','sex':1,'url':'http://heisetoufa.iteye.com','devtype':1,'loginip':'10.10.10.10'}}";

		JSONObject json = new JSONObject(result);
		JSONObject error = json.getJSONObject("error");
		if (error.getInt("code") == 0) {
			JSONObject user = json.getJSONObject("loginStr");
			long userId = user.getLong("userid");
			System.out.println("userID:" + userId);
			System.out.println("info:" + error.getString("info"));
			System.out.println("name:" + user.getString("name"));
		} else {
		}
	}
}


输出:
userID:12345
info:错误由未知错误引起
name:黑色头发

黑色头发:http://heisetoufa.iteye.com/

你可能感兴趣的:(json,JSONObject,JsonArray)