“)); 的System.out.println(arr.getJSONObject(I).getString( “名字”));}
这是我的JSON字符串
[ { “href”:“\ / api \ / rest \ / v1 \ / protocols \ / BACnet的 </跨度> \ /本地\ /对象\ /模拟值\ / 1“ , “name ”:“analogValue_1” }, { “href”:“\ / api \ / rest \ / v1 \ / protocols \ / BACnet的 </跨度> \ /本地\ /对象\ /模拟值\ / 9” , “name”:“analogValue_9” }, { “href”:“\ / api \ / rest \ / v1
从您的评论我们可以看到您正在使用 okhttp3.internal.http.RealResponseBody 。自从 toString() 方法没有被覆盖,使用默认实现就是这个原因 System.out.println(response.body().toString()); 版画 okhttp3.internal.http.RealResponseBody@66cdc1bd 。
okhttp3.internal.http.RealResponseBody
toString()
System.out.println(response.body().toString());
okhttp3.internal.http.RealResponseBody@66cdc1bd
要获得实际的原始响应,请使用 string() 方法:
string()
JSONArray arr = new JSONArray(responseBody.string());
根据 文件 (RealResponseBody扩展了ResponseBody):
String string() Returns the response as a string decoded with the charset of the Content-Type header.
这也已经讨论过了 这里 顺便说说。
修复你的json。 1.将方括号更改为花括号。 2. json中的每个字典都是一个必须具有相应键的值。您的代码应如下所示:
public static void main(String[] args) { String myJSON = "{data_0:\n" + " {\n" + " \"href\": \"\\/api\\/rest\\/v1\\/protocols\\/bacnet\\/local\\/objects\\/analog-value\\/1\",\n" + " \"name\": \"analogValue_1\"\n" + " },\n data_1:" + " {\n" + " \"href\": \"\\/api\\/rest\\/v1\\/protocols\\/bacnet\\/local\\/objects\\/analog-value\\/9\",\n" + " \"name\": \"analogValue_9\"\n" + " },\n data_2:" + " {\n" + " \"href\": \"\\/api\\/rest\\/v1\\/protocols\\/bacnet\\/local\\/objects\\/analog-value\\/2\",\n" + " \"name\": \"analogValue_2\"\n" + " },\n data_3:" + " {\n" + " \"href\": \"\\/api\\/rest\\/v1\\/protocols\\/bacnet\\/local\\/objects\\/analog-value\\/8\",\n" + " \"name\": \"analogValue_8\"\n" + " },\n data_4:" + " {\n" + " \"href\": \"\\/api\\/rest\\/v1\\/protocols\\/bacnet\\/local\\/objects\\/analog-value\\/7\",\n" + " \"name\": \"analogValue_7\"\n" + " },\n data_5:" + " {\n" + " \"href\": \"\\/api\\/rest\\/v1\\/protocols\\/bacnet\\/local\\/objects\\/analog-value\\/3\",\n" + " \"name\": \"analogValue_3\"\n" + " },\n data_6:" + " {\n" + " \"href\": \"\\/api\\/rest\\/v1\\/protocols\\/bacnet\\/local\\/objects\\/analog-value\\/6\",\n" + " \"name\": \"analogValue_6\"\n" + " },\n data_7:" + " {\n" + " \"href\": \"\\/api\\/rest\\/v1\\/protocols\\/bacnet\\/local\\/objects\\/analog-value\\/5\",\n" + " \"name\": \"analogValue_5\"\n" + " },\n data_8:" + " {\n" + " \"href\": \"\\/api\\/rest\\/v1\\/protocols\\/bacnet\\/local\\/objects\\/analog-value\\/4\",\n" + " \"name\": \"analogValue_4\"\n" + " }\n" + "}"; JSONObject jsonObject = new JSONObject(myJSON); System.out.println("jsonObject: " + jsonObject.toString()); List<String> list = new ArrayList<String>(); System.out.println("jsonObject length: " + jsonObject.length()); for (int i = 0; i < jsonObject.length(); i++) { list.add(jsonObject.getJSONObject("data_" + i).toString()); System.out.println(jsonObject.getJSONObject("data_" + i)); } }
我添加了从data_0到data_8的密钥。然后创建一个列表。可能这并不能完全解决你的问题,但最不能说明你犯了什么错误。