2015-05-17

[Java] 解讀JSON格式的字串. Parse JSON String

This is example code to parse JSON String by Java.


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


String jsonString;

/* Put you JSON String to jsonString */

JSONArray myJsonArray = null;
try {
    myJsonArray = new JSONArray(jsonString);
} catch (JSONException ignored) {
    Log.e(DEBUG_TAG, "json parse Error!!");
    return;
}


for (int i = 0; i < myJsonArray.length(); i++) {
    try {
        // get each element of the array
        JSONObject oneObject = myJsonArray.getJSONObject(i);
        if (oneObject == null) {
            continue;
        }
        
        // get items from the element...
        String column01 = oneObject.getString("column01");
        String column02 = oneObject.getString("column02");
        JSONArray column03 = oneObject.getJSONArray("column03");
        
        /* do something  */

    } catch (JSONException ignored) {
        Log.e(DEBUG_TAG, "json parse Error!!");
    }
}