0

我有 JSON 格式的字符串。例如:

{
   "blockedStatus":true,
   "cars":[
      "RAW:123",
      "TVU:123"
   ],
   "phones":[
      "370665566",
      "3706324231"
   ]
}

这是服务器的输出。我需要获得单独的值,但我不知道该怎么做。

试过这个:

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
}

JSONTokener tokener = new JSONTokener(builder.toString());              
JSONArray finalResult = new JSONArray(tokener);
Log.e("IO-OUTPUT", builder.toString());  //prints json output
Log.e("finalResult (1)", finalResult.getString(1));

但我得到蚂蚁例外:

W/System.err(31249): org.json.JSONException: Value {"blockedStatus":true,"cars":["RAW"],"phones":["65431"]} of type org.json.JSONObject cannot be converted to JSONArray

还有另一种获取价值的方法吗?因为计算符号并从中获取值太难了

4

2 回答 2

0

改变

JSONTokener tokener = new JSONTokener(builder.toString());              
JSONArray finalResult = new JSONArray(tokener);

JSONObject jsonObject = new JSONObject(builder.toString());              
JSONArray carsResult = jsonObject.getJSONArray("cars");
JSONArray phoneResult = jsonObject.getJSONArray("phones");

您的字符串 rapresent aJSONObject包含两个JSONArray'scarsphones, 和一对 key/value blockedStatus

此外,如果您阅读 logcat,它会说:

type org.json.JSONObject cannot be converted to JSONArray

您不能将 a 转换JSONObject为 a JSONArray,这意味着您有一个JSONObject

于 2013-05-15T11:09:29.517 回答
0

尝试这个

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips  = response.getEntity().getContent();
responseString = response.toString();
responseString = intputStreamToStringConvertor(ips);
JSONObject object = new JSONObject(responseString);
Boolean status = object.getBoolean("blockedStatus");
JsonArray cars = object.getJSONArray("cars");
JsonArray phones = object.getJSONArray("phones");
于 2013-05-15T11:18:17.307 回答