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.