1

我正在尝试解析 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");
        }

    }

}

那么,你能看出这里的问题吗?它有什么问题?

4

1 回答 1

3

你的jsonJSONArray不是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");
于 2013-04-26T12:07:01.040 回答