4

我在尝试解析 JSON 数据时遇到 JSON 异常,因为我正在关闭 Web 服务。

我已经查看了与此异常有关的相关问题,但我仍然无法提出解决方案。

这是来自网络服务的 Json 数组

[
   {
      "created_at":"2013-03-18T21:30:19Z",
      "id":1,
      "name":"latte",
      "price":"5",
      "updated_at":"2013-03-18T21:30:19Z"
   },
   {
      "created_at":"2013-03-18T21:30:41Z",
      "id":11,
      "name":"black",
      "price":"2",
      "updated_at":"2013-03-18T21:30:41Z"
   },
   {
      "created_at":"2013-03-19T09:38:31Z",
      "id":21,
      "name":"Tea",
      "price":"2",
      "updated_at":"2013-03-19T09:39:02Z"
   }
]

这是使用解析器作为后台任务的类的相关部分

public class SpinnerDemo extends Activity {

    //JSON node names
    private static final String TAG_DATA = "data";
    private static final String TAG_CREATED_AT = "created_at";
    private static final String TAG_ID_DRINK = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_UPDATED_AT = "updated_at";
    private static final String MAP_API_URL = "http://notTheActualURL.com/drinks.json";
    private BackGroundTask bgt;

    Spinner drinkField;

    ArrayList<Drink> drinkList = new ArrayList<Drink>();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.spinner_main);
        buildDrinkDropDown();
    }

    private void buildDrinkDropDown() {

        List<NameValuePair> apiParams = new ArrayList<NameValuePair>(1);
        apiParams.add(new BasicNameValuePair("call", "drinkList"));

        bgt = new BackGroundTask(MAP_API_URL, "GET", apiParams);

        try {
            JSONObject drinkJSON = bgt.execute().get();
            // Getting Array of drinks
            JSONArray drinks = drinkJSON.getJSONArray(TAG_DATA);

            // looping through All drinks
            for (int i = 0; i < drinks.length(); i++) {

                JSONObject d = drinks.getJSONObject(i);

                // Storing each json item in variable

                String id = d.getString(TAG_ID_DRINK);
                String createdAt = d.getString(TAG_CREATED_AT);
                String updatedAt = d.getString(TAG_UPDATED_AT);
                String price = d.getString(TAG_PRICE);
                String name = d.getString(TAG_NAME);



                // add drink
                drinkList.add(new Drink( createdAt ,id, name, price,updatedAt ));
            }

这是进行解析的实际类

package com.android.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class BackGroundTask extends AsyncTask<String, String, JSONObject> {

     List<NameValuePair> postparams = new ArrayList<NameValuePair>();
     String URL = null;
     String method = null;

     static InputStream is = null;
     static JSONObject jObj = null;
     static String json = "";

     public BackGroundTask(String url, String method, List<NameValuePair> params) {
      this.URL = url;
      this.postparams = params;
      this.method = method;
     }

     @Override
     protected JSONObject doInBackground(String... params) {
      // TODO Auto-generated method stub
      // Making HTTP request
      try {
       // Making HTTP request
       // check for request method

       if (method.equals("POST")) {
        // request method is POST
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(URL);
        httpPost.setEntity(new UrlEncodedFormEntity(postparams));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

       } else if (method == "GET") {
        // request method is GET
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String paramString = URLEncodedUtils
          .format(postparams, "utf-8");
        URL += "?" + paramString;
        HttpGet httpGet = new HttpGet(URL);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
       }

      } catch (UnsupportedEncodingException e) {
       e.printStackTrace();
      } catch (ClientProtocolException e) {
       e.printStackTrace();
      } catch (IOException e) {
       e.printStackTrace();
      }

      try {

       BufferedReader reader = new BufferedReader(new InputStreamReader(
         is, "utf-8"), 8);
       StringBuilder sb = new StringBuilder();
       String line = null;
       while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
       }
       is.close();
       json = sb.toString();
      } catch (Exception e) {
       Log.e("Buffer Error", "Error converting result " + e.toString());
      }

      // try parse the string to a JSON object
      try {
       jObj = new JSONObject(json);
      } catch (JSONException e) {
       Log.e("JSON Parser", "Error parsing data TEST " + e.toString());
      }

      // return JSON String
      return jObj;

     }
    }

这是日志猫的例外

03-26 11:32:49.637: E/JSON Parser(714): Error parsing data TEST org.json.JSONException: Value [{"id":1,"created_at":"2013-03-18T21:30:19Z","updated_at":"2013-03-18T21:30:19Z","price":"5","name":"latte"},{"id":11,"created_at":"2013-03-18T21:30:41Z","updated_at":"2013-03-18T21:30:41Z","price":"2","name":"black"},{"id":21,"created_at":"2013-03-19T09:38:31Z","updated_at":"2013-03-19T09:39:02Z","price":"2","name":"Tea"}] of type org.json.JSONArray cannot be converted to JSONObject

还有另一个错误显示 spinnerDemo 类中的空点异常,尽管我认为这是上一个异常的结果

03-26 11:32:49.707: E/AndroidRuntime(714): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.main/com.android.main.SpinnerDemo}: java.lang.NullPointerException

对此的任何建议或帮助将不胜感激

4

3 回答 3

6

如在日志中:

org.json.JSONArray 无法转换为 JSONObject

因为您获得JSONArray的是根元素,而不是JSONObject但您正试图将其转换为 JSONObject。目前您正在获得以下 json 结构:

[     //<<<<<<<<< JSONArray
   {      //<<<<<<<<< JSONObject

   },
  ....
]

您需要将 json 字符串转换为JSONArray然后从中JSONObject提取

JSONArray drinkJSON = bgt.execute().get();

您还需要将doInBackground方法返回类型更改为JSONArray

于 2013-03-26T11:53:59.027 回答
1
        HttpResponse responseGet = client.execute(get);
        HttpEntity resEntityGet = responseGet.getEntity();

        if (resEntityGet != null) {
            String response = EntityUtils.toString(resEntityGet);
        }

使用此行首先获取数组

JSONArray valarray = new JSONArray(response);

然后循环进入对象内部

for (int i = 0; i < valarray.length(); i++) {

    JSONObject arr = valarray.getJSONObject(i); 

}

这对我来说非常有用。

于 2013-03-26T11:56:52.613 回答
0

你的回报 json 是jsonarray,但你可以得到jsonobject

所以,我们可以使用,

 JSONArray drinkJSON = bgt.execute().get();

BackGroundTask课堂上, doInBackground方法

protected JSONArray doInBackground(String... params) {

以及对象创建的变化,

     JsonArray jobj;
try {
       jObj = new JSONArray(json);
      } catch (JSONException e) {
       Log.e("JSON Parser", "Error parsing data TEST " + e.toString());
      }
于 2013-03-26T11:54:30.330 回答