我正在尝试解析Android中的JSON代码,而我在解析时遇到上述错误。
这是我要解析的JSON:
[{"value":"91.84","timestamp":"2012-10-11 14:12:13"}]
以下是我解析它的方式:
InputStream inputStream = null;
String result = null;
HttpResponse response;
BufferedReader reader;
JSONObject jObject;
JSONArray jArray = null;
String aJsonString1;
String aJsonString2;
public class ReadJSON extends AsyncTask<String, Void, String> {
protected String doInBackground(String... url) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("url is written here");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
jObject = new JSONObject(sb.substring(0));
for (int i=0; i < jArray.length(); i++)
{
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("value");
String oneObjectsItem2 = oneObject.getString("timestamp");
}
aJsonString1 = jObject.getString("value");
aJsonString2 = jObject.getString("timestamp");
return aJsonString1;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON",e.getMessage() + " " + e);
}
return null; // Error case
}
protected void onPostExecute(String result) {
textView.setText(aJsonString1);
if(aJsonString1==null){
textView.setText("nothing to show");
}
}
}
那么,你能在这里看到问题吗?这有什么问题?
答案 0 :(得分:3)
你的json是JSONArray
而不是JSONObject
更改您的代码,
json有多个JSONObject
,然后使用以下代码
JSONArray jsonArray = new JSONArray(sb);
for (int i=0; i < jsonArray.length(); i++)
{
JSONObject oneObject = jsonArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("value");
String oneObjectsItem2 = oneObject.getString("timestamp");
}
假设json有单JSONObject
aJsonString1 = jsonArray.getJSONObject(0).getString("value");
aJsonString2 = jsonArray.getJSONObject(0).getString("timestamp");