Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

How to access Object value in unnamed JSON Object array in Java?

  • 01-09-2017 02:57PM
    #1
    Registered Users, Registered Users 2 Posts: 266 ✭✭


    [{
    	"name": "requisitions",
    	"id": "PR2"
    }]
    

    I am trying to access 'id' in the above JSONObject but the array is unnamed so how can I access it.

    The JSONObject result below contains the above JSONObject
    JSONObject result = new JSONObject(obj.getString("RESULT"));
                    JSONArray resultArray = result.getJSONArray(????);
    ... and then for loop through resultArray.length() with resultArray.getJSONObject(i).getString("id");
    

    But I cant seem to acess the JSONArray. I also tried...
    JSONArray resultArray = new JSONArray(result.toString());
    

    Any help with this is much appreciated.


Comments

  • Registered Users, Registered Users 2 Posts: 7,205 ✭✭✭Talisman


    If obj.getString("RESULT") is returning the array string ( i.e. '[{ "name": "requisitions", "id": "PR2" }]' ) then you pass it directly to the JSONArray constructor.

    The following code uses a for loop just in case there is more than one object within the array and you need to iterate through them.
    JSONArray result = new JSONArray( obj.getString("RESULT") );
    for (int i=0; i < result.length(); i++) {
      JSONObject resultObj = result.getJSONObject( i );
      /* resultObj : { "name": "requisitions", "id": "PR2" } */
      String resultObjName = resultObj.getString("name");
      String resultObjId = resultObj.getString("id");
    }
    

    If there's only a single object or you're only interested in the first element then you don't need the loop:
    JSONArray result = new JSONArray( obj.getString("RESULT") );
    JSONObject resultObj = result.getJSONObject(0);
    String resultObjName = resultObj.getString("name");
    String resultObjId = resultObj.getString("id");
    


  • Registered Users, Registered Users 2 Posts: 275 ✭✭rocketspocket


    Stackoverflow is your friend on these type of questions.


Advertisement