-2

I'm getting the above-mentioned error while trying to extract data from JSONObject.My objective is to extract the "transactionId" data and store it in a variable for future use.

What I have so far:

protected void onPostExecute(String result) {

        super.onPostExecute(result);
        if (pd.isShowing()) {
            pd.dismiss();
        }
       /*txtJson.setText(result);*/


        JSONObject jsonarray;
        try {
            jsonarray = new JSONObject(result);
            for (int i = 0; i < jsonarray.length(); i++) {
                JSONObject mJsonObject = jsonarray.getJSONObject(i);
                Log.d("OutPut", mJsonObject.getString("transactionId"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
}

My JSON Object is shown below:

{  
 "merchantId":"X",
 "transactionId":"Y"
}

I'm new to Programming so any help would be appreciated.

Meenal
  • 2,879
  • 5
  • 19
  • 43
Aabhushan Gautam
  • 208
  • 1
  • 12
  • 1
    `JSONObject jsonarray` what is the thought process here? – Tim Sep 25 '17 at 11:09
  • 2
    Possible duplicate of [How to parse JSON in Android](https://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) – Tim Sep 25 '17 at 11:09
  • No need of `for loop`, if your JSON only have single object – Parag Jadhav Sep 25 '17 at 11:12
  • i think your jsonarray should be an JSONArray and if so then you can get all the elements in the array and can access there data – RajatN Sep 25 '17 at 11:17

1 Answers1

1

Try this code

 JSONArray jsonarray;
    try {
        jsonarray = new JSONArray(result);
        for (int i = 0; i < jsonarray.length(); i++) {
            JSONObject mJsonObject = jsonarray.optJSONObject(i);
            Log.d("OutPut", mJsonObject.optString("transactionId"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

Also, if there is single ITEM in your JSONArray, you can remove forLoop.

And, if the response received is JSONObject then,

 JSONObject jsonObject;
    try {
        jsonObject = new JSONObject(result);
        Log.d("OutPut", jsonObject.optString("transactionId"));

    } catch (JSONException e) {
        e.printStackTrace();
    }
Meenal
  • 2,879
  • 5
  • 19
  • 43