bicycle_guy
bicycle_guy

Reputation: 299

Build JSONArray of JSONobjects from a string of JSONObjects?

I am trying to take a file containing JSON objects and put them into a JSONArray.

After removing the initial characters, the string of JSON objects looks like this:

{ "id" : "ajson1", "parent" : "#", "text" : "Simple root node" },
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" }

I need to take each object and store it in a JSONArray. This is what I have now:

public JSONArray getJSON(File inputFile) throws IOException, JSONException {
    String content = FileUtils.readFileToString(inputFile);

    content = content.substring(4, content.length() - 1);

    JSONObject jsonObject = new JSONObject(content);

    String[] names = JSONObject.getNames(jsonObject);

    JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));

    return jsonArray;
}

The correct values are not being stored in the JSONArray. How should I proceed?

Upvotes: 1

Views: 60

Answers (1)

JstnPwll
JstnPwll

Reputation: 8695

Why not simply:

public JSONArray getJSON(File inputFile) throws IOException, JSONException {
    String content = FileUtils.readFileToString(inputFile);
    content = content.substring(4, content.length() - 1);
    JSONArray jsonArray = new JSONArray("[" + content + "]");
    return jsonArray;
}

Upvotes: 1

Related Questions