1

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?

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is working perfectly. I don't know why I didn't just try to insert the string directly into the JSONArray like that.

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.