0

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.

1
  • My code is unchanged. My comment was referring to @toltman's line of code. Commented May 30, 2018 at 18:06

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

2 Comments

This compiles but gives the error: "java.lang.String cannot be cast to org.json.simple.JSONObject"
That's odd because that code doesn't attempt to cast a String to a JSONObject anywhere. Is there someplace else in your code that might be doing that cast?

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.