-3

I use code above to parse JSON in a try-catch.

        JSONArray jsonRootObject = new JSONArray(text);
        JSONArray jsonArray = jsonRootObject.optJSONArray(2);

        name = jsonArray.toString();
        Toast.makeText(MainActivity.this, name, Toast.LENGTH_LONG).show();

I use 2 as index in code below, because I would get values from candidates. I think, that is strange, because there isn't key-value pairs in array. I would like to get only the first key from this array (In this example subtest1.), its value isn't make sense.

{
    "images": [
    {
        "time": 2.86091,
        "transaction":
        {
            "status": "Complete",
            "subject": "test2",
            "confidence": 0.77,
            "gallery_name": "gallerytest1",
        },
        "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"
        }
        ]
    } ]
}
plaidshirt
  • 5,189
  • 19
  • 91
  • 181

2 Answers2

1

your parser should be like.FYI JSONArray does not have key-value pairs but JSONObject does.

JSONObject root = new JSONObject(text);
JSONArray jarray = root.optJSONArray("images);
if(jarray != null){
   JSONObject jObject = jarray.optJSONObject(0);
   if(jObject != null){
      JSONArray candidates = jObject.optJSONArray("candidates");
      JSONObject jObj = jarray.optJSONObject(0);
      if(jObj != null){
          String subTest =  jObj.optString("subtest1");
      }
   }
}
Ravi Theja
  • 3,371
  • 1
  • 22
  • 34
1

Try this and see if it solves your problem

 JSONArray CandidatesArr = new JSONArray(jsonRootObject.getString("candidates"));
        JSONObject CandidatesOBJ = CandidatesArr.getJSONObject(0);
String name=CandidatesOBJ.getString("subtest1");

Edit

To check if your key subset1 exists or not try the following code:

String name=""
    if(CandidatesOBJ.has("subtest1")){
name=CandidatesOBJ.getString("subtest1");
    }
Shafayat Mamun
  • 439
  • 1
  • 6
  • 22