搜尋此網誌

2014年10月25日 星期六

【Android】array to json/json to array

private void JSONEncode() throws JSONException {
        JSONArray jsonArray = new JSONArray();
 
        for (int i = 0; i < name.length; i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", name[i]);
            jsonObject.put("id", id[i]);
            jsonObject.put("score", score[i]);
            jsonArray.put(jsonObject);
        }
 
        Log.i("JSON String", jsonArray.toString());
        JSONString = jsonArray.toString();
    }
 
    private void JSONDecode() throws JSONException {
        JSONArray jsonArray = new JSONArray(JSONString);
        Log.i("Number of Entries", Integer.toString(jsonArray.length()));
 
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString("name");
            int id = jsonObject.getInt("id");
            double score = jsonObject.getDouble("score");
            Log.i("Entry", "name: " + name + ", id: " + id + ", score: " + score);
        }
    }
ref:Alan's Development Notes

沒有留言: