-1

Sample code of JSON:

[  
   {  
      "name":"Norway",
      "languages":[  
         "no",
         "nb",
         "nn"
      ]
   }
]

I'm trying to use Java to validate the response "languages" contains "no", and my code below fyi but how can I validate this, appreciate any responses.

    //Fetching response in JSON
    JSONArray jsonResponse = new JSONArray(resp.asString());

    //Fetching value of languages parameter
    JSONArray languages = jsonResponse.getJSONObject(0).getJSONArray("languages");
Cathy
  • 1
  • 2
  • Is `languages` a JSON string? Is it a JSON object? Is it a JSON array? – Sotirios Delimanolis Nov 12 '15 at 18:50
  • It looks like it's an array according to the sample. – Mark Sholund Nov 12 '15 at 18:52
  • I've referenced http://stackoverflow.com/questions/1568762/accessing-members-of-items-in-a-jsonarray-with-java and in my case, i simply want to validate certain value exists, which is "no" here, wondering whether there is any existed asserts that perform this, appreciate any of your responses – Cathy Nov 12 '15 at 19:09

1 Answers1

1

Since JSONArray doesn't seem to have something like a contains method, I think the best solution is just a simple for loop:

boolean containsNo = false;

for (int i = 0; i < languages.length(); i++) {
    if ("no".equals(languages.getString(i))) {
        containsNo = true;
        break;
    }
}

System.out.println(containsNo);  // prints "true"
andersschuller
  • 13,509
  • 2
  • 42
  • 33