簡體   English   中英

無法將字符串轉換為 JSONObject

[英]Not able to convert String to JSONObject

我正在獲取一個輸入流並將其轉換為String然后轉換為JSONObject

下面是將輸入流轉換為字符串,然后是 JSONObject 的片段。

但是在轉換為 json 對象(第 6 行)后,我只得到第一個object而不是所有objects

你能告訴我為什么我只得到一個對象而不是所有的 n 個對象

InputStream in = new BufferedInputStream(conn.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
int i =result.indexOf("{");
String forResult=result.substring(i);
System.out.println(forResult); // Result 1
JSONObject jsonObject = new JSONObject(forResult); // Line 6
System.out.println(jsonObject); // Result 2

將其轉換為 String 后,它看起來像這樣

結果 -1

{  
   "test_expr":"",
   "val_expr":"someVale",
   "val_advanced":true,
   "machine_val":null
}, {...// n times}

結果 2 - 僅第一個對象

{  
     "test_expr":"",
       "val_expr":"someVale",
       "val_advanced":true,
       "machine_val":null
    } 

謝謝,請容忍我的無知,因為我完全是 Java 新手

因為你的 json 無效。 JSONObject之間有一個逗號。

改成這個。

{
    {
    "test_expr":"",
    "val_expr":"someVale",
    "val_advanced":true,
    "machine_val":null
    },
    {
    "test_expr":"",
    "val_expr":"someVale",
    "val_advanced":true,
    "machine_val":null
    }
    ...
}

或者

 [
    {
    "test_expr":"",
    "val_expr":"someVale",
    "val_advanced":true,
    "machine_val":null
    },
    {
    "test_expr":"",
    "val_expr":"someVale",
    "val_advanced":true,
    "machine_val":null
    }
    ...
]

JSONObject的來源

/**
 * Creates a new {@code JSONObject} with name/value mappings from the JSON
 * string.
 *
 * @param json a JSON-encoded string containing an object.
 * @throws JSONException if the parse fails or doesn't yield a {@code
 *     JSONObject}.
 */
public JSONObject(String json) throws JSONException {
    this(new JSONTokener(json));
}

所以一個包含對象的 JSON 編碼字符串(如 {})。

// make sure that you result contain {}
result = "{your data here}"
JSONObject json_data = new JSONObject(result);

如果你使用JSONArray ,你應該在你的JSON包含 []

result = "[json data]";
JSONArray jsonArray = new JSONArray(result);

好吧,多個 json 的串聯不是有效的 json。 您的解析庫應該拒絕這樣的輸入,但它似乎只是在有效對象的末尾停止。

您可以將列表包裝成一個數組:[{...},{...},{...}]。 然后解析器將能夠正確地將其解釋為數組。

我猜你得到的是 JSONArray 對象而不是 JSONObject。 為什么需要獲取結果的子字符串? Json 數組可以以 [. 查看 JSONObject 和 JSONArray 之間的區別。 JSONObject 和 JSONArray 的區別

感謝 Sotirios Delimanolis。

我可以通過使用 JSONParser 來解決這個問題

InputStream in = new BufferedInputStream(conn.getInputStream());
        String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
        JSONParser parser = new JSONParser();
        org.json.simple.JSONArray modelArrary =(org.json.simple.JSONArray) parser.parse(result) ;
        System.out.println(modelArrary);

暫無
暫無

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

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