簡體   English   中英

從一串JSONObjects構建JSONObjects的JSONArray?

[英]Build JSONArray of JSONobjects from a string of JSONObjects?

我正在嘗試將包含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中。 我應該如何進行?

為什么不簡單:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM