2

I am having issues parsing an array of json objects using json-simple.

suppose the following array of report objects:

[
  {
    "title": "Test Object 1",
    "description": "complicated description...",
    "products": null,
    "formats": ["csv"]
  },
  {
    "title": "Test Object 2",
    "description": "foo bar baz",
    "products": ["foo"],
    "formats": ["csv", "pdf", "tsv", "txt", "xlsx"]
  },
  {
    "title": "Test Object 3",
    "description": "Lorem Ipsum stuff...",
    "products": null,
    "formats": ["pdf", "xlsx"]
  }
]

in the following code, after reading in from a file, how could i iterate over each object in the array to perform the operations?

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class JsonReader {

public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(new FileReader("sample.json"));

        //convert object to JSONObject
        JSONObject jsonObject = (JSONObject) obj;

        //reading the string
        String title = (String) jsonObject.get("title");
        String description = (String) jsonObject.get("description");

        //Reading an array
        JSONArray products = (JSONArray) jsonObject.get("products");
        JSONArray formats = (JSONArray) jsonObject.get("formats");

        //Log values
        System.out.println("title: " + title);
        System.out.println("description: " + description);

        if (products != null) {
            for (Object product : products) {
                System.out.println("\t" + product.toString());
            }
        } else {
            System.out.println("no products");
        }

        if (formats != null) {
            for (Object format : formats) {
                System.out.println("\t" + format.toString());
            }
        } else {
            System.out.println("no formats");
        }

    } catch (FileNotFoundException fe) {
        fe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

running the debugger, it seems that the jsonObject is storing the array, but im not sure how to get to it. creating a for each loop doesn't seem to work because the JSONObject is not iteratable.

1
  • It appears the JSON you want to parse is a JSONArray, not a single JSONObject. If that helps. Commented Aug 11, 2017 at 21:47

2 Answers 2

2

You can parse your json file as JSONArray instead of JSONObject

Object obj = parser.parse(new FileReader("sample.json"));

// convert object to JSONArray
JSONArray jsonArray = (JSONArray ) obj;

Then you can traverse through jsonArray.

jsonArray.forEach(item -> {
    System.out.println(item);
    // Do stuff
});
Sign up to request clarification or add additional context in comments.

Comments

0

I think that your JSON is not valid in terms of the JSON Standard (see JSON.org). The JSON should start with '{' and end with '}'. I don't think the array will be accessible in a standard way since it is lacking a key. If it is possible you should put your JSON between (or just concat this to your JSON string in your code):

{ "array": 
    //yourJson 
}

Then you could acsess the Array with something like:

JSONArray array = (JSONArray) jsonObject.get("array");
Iterator iter = array.iterator();


while (iter.hasNext()) {
        System.out.println( ( iter.next() ).get("title") );
    }

1 Comment

No, JSON can start with [. JSON.org mentions both the structures. stackoverflow.com/a/5034547/1776132 has more details

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.