日期:2014-05-16  浏览次数:20459 次

濡備綍媯?煡鏈嶅姟鍣ㄤ腑鐨勫搷搴旀槸JSONAobject杩樻槸JSONArray?

鍘熼棶棰樻潵鑷簬CSDN闂瓟棰戦亾錛屾洿澶氳В鍐蟲柟妗堣錛?a href="http://ask.csdn.net/questions/1855">http://ask.csdn.net/questions/1855

闂鎻忚堪錛?/strong>

 

紼嬪簭涓殑涓?釜鏈嶅姟鍣紝榛樿杩斿洖涓?簺JSONArray銆備絾褰撲竴浜涢敊璇彂鐢熸椂錛屽畠杩斿洖JSONObject閿欒鐨勪唬鐮併?鎴戞兂瑙f瀽json鏉ユ鏌ラ敊璇?涓嬮潰鐨勪唬鐮佺敤鏉ヨВ鏋愰敊璇細

public static boolean checkForError(String jsonResponse) {

    boolean status = false;
    try {

        JSONObject json = new JSONObject(jsonResponse);

        if (json instanceof JSONObject) {

            if(json.has("code")){
                int code = json.optInt("code");
                if(code==99){
                    status = true;
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return status ;
}

浣嗘槸褰?jsonResponse 鍙互杩愯鏃剁‘鑾峰緱 JSONException銆傚畠鏄竴涓狫SONArray錛孞SONArray
涓嶈兘杞崲鎴?JSONOBject銆傚浣曠‘璁?jsonResponse 浼犺繃鏉ョ殑值鏄?JSONArray 杩樻槸 JSONObject ?

瑙e喅鏂規錛?/strong>

棣栧厛鐪嬩笅杩欎袱涓被鍨嬭漿鎹負瀛楃涓插悗鐨勫尯鍒?/span>

  ......
    JSONObject jo = createJSONObject();    
    JSONArray ja = new JSONArray();
    ja.put(jo);        
    System.out.println("jo is "+jo.toString());//{"sex":"鐢?quot;,"username":"ZhangSam","score":123}
    System.out.println("ja is "+ja.toString());//[{"sex":"鐢?quot;,"username":"ZhangSam","score":123}]      
}
public static JSONObject createJSONObject(){
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("username", "ZhangSam");     
        jsonObject.put("sex", "鐢?quot;);
        jsonObject.put("score", new Integer(123));          
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jsonObject;
}


鎵?互浣犺鎯衝啓閮藉兘璇嗗埆鐨勶紝鍙渶姝e垯媯?煡鏄惁[寮?ご鍗衝彲
鐒跺悗鎵嶈兘杩涜浣犵殑杩欎竴姝?濡傛槸闈瀃寮?ご錛孞SONObject json = new JSONObject(jsonResponse);
鍙﹀杩樹竴縐嶆柟娉曞氨鏄湪finally涓鐞?/span>
鏈?悗涓?偣涓庨鏃犲叧鐨勬槸錛孞SONObject涓嶫SONArray鍙互浜掕漿錛?/span>
(toJSONObject/toJSONArray)