繁体   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