Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

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

  • 01-09-2017 2: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: 6,289 ✭✭✭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: 402 ✭✭rocketspocket


    Stackoverflow is your friend on these type of questions.


Advertisement