MickeyTheMouse
MickeyTheMouse

Reputation: 419

Reading an array of Strings in a JSON object in Java

I have a JSON object that looks something like this,

{
  "students": [
    {
      "Name": "Some name",
      "Bucket": 4,
      "Avoids": ["Foo", "Bar"]
    },
    {
      "Name": "Some other name",
      "Bucket": 1,
      "Avoids": ["Some String"]
    }
  ]
}

I'm trying to parse this JSON object in Java.

Here is my Java code:

Object obj = parser.parse(new FileReader("./data.json"));
JSONObject jsonObject = (JSONObject) obj;

JSONArray students = (JSONArray) jsonObject.get("students");
Iterator<JSONObject> studentIterator = students.iterator();

while (studentIterator.hasNext()) {
    JSONObject student = (JSONObject) studentIterator.next();
    String name = (String) student.get("Name");

    double bucketValue;

    if (student.get("Bucket") instanceof Long) {
        bucketValue = ((Long) student.get("Bucket")).doubleValue();
    } else {
        bucketValue = (double) student.get("Bucket");
    }

    JSONArray avoids = (JSONArray) student.get("Avoids");
    Iterator<JSONObject> avoidsIterator = avoids.iterator();

    while (avoidsIterator.hasNext()) {
        String s = (String) avoidsIterator.next();
    }
}

Everything up till here works until I try to parse the "Avoids" array. This array is guaranteed to have only Strings. However, when I do

String s = (String) avoidsIterator.next();

I get,

error: incompatible types: JSONObject cannot be converted to String

Which is expected. But I know for sure that all the values in the Avoids array are Strings. How do I get all those strings?

There are also instances where the Avoids array is empty.

Upvotes: 0

Views: 54

Answers (2)

Hemant Patel
Hemant Patel

Reputation: 3260

Change your avoidsIterator as iterator of string, not iterator of JsonObject

Iterator<String> avoidsIterator = avoids.iterator();
while (avoidsIterator.hasNext()) {
    String s =  avoidsIterator.next();
    System.out.println(s);     
}

Output

Foo
Bar
Some String

Upvotes: 1

toltman
toltman

Reputation: 487

I don't see why this shouldn't work.

String s = avoidsIterator.next().toString();

Upvotes: 0

Related Questions