android 之JSON

1、android 读取json数据(遍历JSONObject和JSONArray)

public String getJson(){  
        String jsonString = "{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack\"},{\"name\":\"lucy\"}]}";//json字符串  
        try {  
            JSONObject result = new JSONObject(jsonstring);//转换为JSONObject  
            int num = result.length();  
            JSONArray nameList = result.getJSONArray("name");//获取JSONArray  
            int length = nameList.length();  
            String aa = "";  
            for(int i = 0; i < length; i++){//遍历JSONArray  
                Log.d("debugTest",Integer.toString(i));  
                JSONObject oj = nameList.getJSONObject(i);  
                aa = aa + oj.getString("name")+"|";  
                  
            }  
            Iterator<?> it = result.keys();  
            String aa2 = "";  
            String bb2 = null;  
            while(it.hasNext()){//遍历JSONObject  
                bb2 = (String) it.next().toString();  
                aa2 = aa2 + result.getString(bb2);  
                  
            }  
            return aa;  
        } catch (JSONException e) {  
            throw new RuntimeException(e);  
        }  
    }  
   

 JSONArray的合并

在Android开发过程中,需要处理解析服务器JSON数据时,或需要进行两个或多个JSONArray合并操作。

比如在进行LIstView的动态更新时。

在此提供一种JSONArray合并的方法,方便需要时调用。

public static JSONArray joinJSONArray(JSONArray mData, JSONArray array) {  
    StringBuffer buffer = new StringBuffer();  
    try {  
        int len = mData.length();  
        for (int i = 0; i < len; i++) {  
            JSONObject obj1 = (JSONObject) mData.get(i);  
            if (i == len - 1)  
                buffer.append(obj1.toString());  
            else  
                buffer.append(obj1.toString()).append(",");  
        }  
        len = array.length();  
        if (len > 0)  
            buffer.append(",");  
        for (int i = 0; i < len; i++) {  
            JSONObject obj1 = (JSONObject) array.get(i);  
            if (i == len - 1)  
                buffer.append(obj1.toString());  
            else  
                buffer.append(obj1.toString()).append(",");  
        }  
        buffer.insert(0, "[").append("]");  
        return new JSONArray(buffer.toString());  
    } catch (Exception e) {  
    }  
    return null;  
}  

 

你可能感兴趣的:(android)