0

I am writing a Java function that restructures some JSON I am getting from a server and I am running into an issue trying to create a JSONArray:

JSONObject jsonObject = jsonObj.getJSONObject("facet_counts").getJSONObject("facet_fields");
Iterator<String> keys = jsonObject.keys();
jsonStr = jsonStr + "\"facetCounts\": {";
    while(keys.hasNext()) {
        String key = keys.next();
        jsonStr = jsonStr + "\"" + key + "\":";
        if (jsonObject.get(key) instanceof JSONArray) {
            JSONArray facets = jsonObject.get(key);

I am checking if jsonObject.get(key) is an instanceof JSONArray, but it keeps throwing the error incompatible types: java.lang.Object cannot be converted to org.json.JSONArray.

1
  • 1
    Please read the Javadoc for JSONObject. You need to call getJSONArray Commented Oct 12, 2022 at 0:18

1 Answer 1

0

Thanks to @tgdavies for their comment, was able to get it working by doing this:

JSONObject jsonObject = jsonObj.getJSONObject("facet_counts").getJSONObject("facet_fields");
Iterator<String> keys = jsonObject.keys();
    jsonStr = jsonStr + "\"facetCounts\": {";
    while(keys.hasNext()) {
        String key = keys.next();
        jsonStr = jsonStr + "\"" + key + "\":";
        if (jsonObject.get(key) instanceof JSONArray) {
            JSONArray facets = new JSONArray(jsonObject.getJSONArray(key).toString());
Sign up to request clarification or add additional context in comments.

Comments

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.