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(); } }
//jsonStr={"mobile":[{"name":"android"},{"name":"iphone"}]} //解析json object 和 json arrary 混合对象 private void parserJson2(String jsonStr) { try { JSONObject mjsonObject=new JSONObject(jsonStr); JSONArray jsonArray=mjsonObject.getJSONArray("mobile"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject=jsonArray.getJSONObject(i); System.out.println(jsonObject.get("name")); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
}