简体   繁体   中英

Using Json-simple to parse an array of objects from a file

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.

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
});

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") );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM