Tuesday, March 17, 2015

Parsing JSON Data

Example of Json Data

JSON format

[
{
"procedureId":1,
"planName":"Test 1",
"stepName":"Test step1"
},
{
"procedureId":2,
"planName":"Test 2",
"stepName":"Test step2"
}
]

Parse it like this

public List<Department> parseDepartmentJson(String response) {

    List<Department> result = new ArrayList<>();

    try {
        JSONArray jsonArray = new JSONArray(response);

        for (int i = 0; i < jsonArray.length(); i++) {

            JSONObject jsonObj = jsonArray.getJSONObject(i);
            Department departmentObj = new Department();

            if (!jsonObj.isNull("procedureId"))
                departmentObj.setProcedureId(jsonObj.getInt("procedureId"));

            if (!jsonObj.isNull("planName"))
                departmentObj.setPlanName(jsonObj.getString("planName"));

            if (!jsonObj.isNull("stepName"))
                departmentObj.setStepName(jsonObj.getString("stepName"));

            result.add(departmentObj);
        }  

     } catch (JSONException e) {
        e.printStackTrace();
        Log.e(TAG, e.getMessage(), e);
    }
}

To check whether the JSON value exists or not, there are 2 methods

'HAS' - Returns true if this object has a mapping for name.
The mapping may be NULL.
if (json.has("status")) String status = json.getString("status")); if (json.has("club")) String club = json.getString("club"));
     
'isNull' - Returns true if this object has no mapping for name or if it has a
mapping whose value is NULL.
if (!json.isNull("club")) String club = json.getString("club"));
 
Here is the other example
[ 
{
  "name" : "Test",
  "id" : 512
}, {
  "name" : "Test2",
  "id" : 573
}, {
  "name" : "Test3",
  "id" : 585
}
]

Parse Like this
ArrayList<String> arrProducts = new ArrayList<String>();

try {
    JSONArray valarray = new JSONArray(jsonstring);
    for (int i = 0; i < valarray.length(); i++) {

        String str = valarray.getJSONObject(i).getString("name");
        arrProducts.add(str);
    }
} catch (JSONException e) {
    Log.e("JSON", "There was an error parsing the JSON", e);
}