【问题标题】:Build JSONArray of JSONobjects from a string of JSONObjects?从一串 JSONObjects 构建 JSONobjects 的 JSONArray?
【发布时间】:2015-11-18 15:59:47
【问题描述】:

我正在尝试获取一个包含 JSON 对象的文件并将它们放入 JSONArray。

去掉开头的字符后,JSON 对象的字符串如下所示:

{ "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" }

我需要获取每个对象并将其存储在 JSONArray 中。这就是我现在拥有的:

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

JSONArray 中未存储正确的值。我应该如何进行?

【问题讨论】:

    标签: java json


    【解决方案1】:

    为什么不简单:

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

    【讨论】:

    • 谢谢!这是完美的工作。我不知道为什么我不只是尝试将字符串直接插入到 JSONArray 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多