0

I have JSON code like above, as a response:

"candidates": [
{
  "subtest1": "0.802138030529022",
  "enrollment_timestamp": "1416850761"
},
{
  "elizabeth": "0.802138030529022",
  "enrollment_timestamp": "1417207485"
},
{
  "elizabeth": "0.777253568172455",
  "enrollment_timestamp": "1416518415"
},
{
  "elizabeth": "0.777253568172455",
  "enrollment_timestamp": "1416431816"
}
]

I try to get names from candidates array.

  public void dataCheck(String text){
    System.out.println("JSON response:");
    System.out.println(text);

    try {
        JSONObject jsonRootObject = new JSONObject(text);
        JSONArray jsonArray = jsonRootObject.optJSONArray("candidates");

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

            String subtest1 = jsonObject.optString("subtest1").toString();

        }
    } catch (JSONException e){
        e.printStackTrace();
    }

}

It is hard, because these values are in an array of an array and without identifier. Identifier is the exact value, so couldn't define variable in my code. I need only first value, like subtest1 in this example.

3
  • I don't see an array in an array. I see JSONObjects in an JSONArray Commented Apr 16, 2016 at 15:35
  • @ligi: Sorry, I've interpret candidates' attributes as another arrays. Commented Apr 16, 2016 at 15:38
  • it should with your code. Is there any exception ?? Commented Apr 16, 2016 at 16:26

1 Answer 1

1
// Get the keys in the first JSON object
Iterator<?> keys = jsonObject.keys();
if (keys.hasNext()) {
    // Get the key
    String key = (String)keys.next();
    String objValue = jsonObject.getString(key);
    ...
}
Sign up to request clarification or add additional context in comments.

5 Comments

But these variable names are given by response. I cannot define them programatically.
I should get 'subtest1', as the value of a String.
See mine updated answer. First, get all keys. If there is a key, get the value of that key. If you also want other keys and values you can replace if with while.
I think this should use jsonRootObject without the for loop according to my code.
But in this case how can it identify candidates array? That should look for key-value pairs in this array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.