如何从混合型json中获取值?

时间:2013-05-15 11:06:08

标签: java android json

我有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

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

2 个答案:

答案 0 :(得分: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");

您的字符串代表JSONObject,其中包含两个JSONArraycarsphones,以及一对键/值blockedStatus

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

type org.json.JSONObject cannot be converted to JSONArray

您无法将JSONObject转换为JSONArray,这意味着您拥有JSONObject

答案 1 :(得分: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");