0

我遇到了 JSON 请求的问题。我正在尝试读取 API 并使用此代码(如下)对其进行解析。一旦我得到这个,我已经让异步工作(到目前为止)我应该设置。我得到的错误在日志下面。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;


public class jsonParser {

    //initialize
    static InputStream stream = null;
    static String result = " ";
    static JSONObject object =null;

    public jsonParser(){

    }

    public JSONObject getJSONfromURL (String url){
        //HTTP call
        try{
            URLConnection connection = new URL(url).openConnection();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 2048 * 16);
            StringBuffer builder = new StringBuffer();
            String line;

            while ((line = reader.readLine()) != null) {
              builder.append(line).append("\n");
            }
            String blah = builder.toString();
            JSONObject jsonObj = new JSONObject(new String(blah));
            JSONArray data = jsonObj.getJSONArray("Categories");

            for(int i=0; i < data.length(); i++)
            {
                 object = data.getJSONObject(i);
                 String id = object.getString("id"); 
                 String value = object.getString("name"); 
                 Log.d("Item name: ", value);
            }




            } catch(Exception e){
                Log.e("Http Error","Error in http connection " + e.toString());

            }


        return object;
    }
}

下面的错误日志

05-12 02:49:44.553: E/Http Error(19288): Error in http connection org.json.JSONException: Value ["Categories",[[{"id":"2","name":"Glass Repair"},{"id":"3","name":"Appliance Repair"},{"id":"4","name":"Air Conditioning"},{"id":"5","name":"Community Involvement"},{"id":"6","name":"Electrical"},{"id":"7","name":"Flooring"},{"id":"8","name":"Heating Repair"},{"id":"9","name":"Landscaping"},{"id":"10","name":"Plumbing"},{"id":"11","name":"Remodeling\/Renovation"},{"id":"12","name":"Window Coverings"}]]] of type org.json.JSONArray cannot be converted to JSONObject
05-12 02:49:44.553: W/dalvikvm(19288): threadid=1: thread exiting with uncaught exception (group=0x40fb6438)
05-12 02:49:44.563: E/AndroidRuntime(19288): FATAL EXCEPTION: main
05-12 02:49:44.563: E/AndroidRuntime(19288): java.lang.NullPointerException
05-12 02:49:44.563: E/AndroidRuntime(19288):    at com.example.hstnc_activity.DisplayServiceActivity$Request.onPostExecute(DisplayServiceActivity.java:116)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at com.example.hstnc_activity.DisplayServiceActivity$Request.onPostExecute(DisplayServiceActivity.java:1)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at android.os.AsyncTask.finish(AsyncTask.java:631)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at android.os.Looper.loop(Looper.java:137)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at android.app.ActivityThread.main(ActivityThread.java:4918)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at java.lang.reflect.Method.invokeNative(Native Method)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at java.lang.reflect.Method.invoke(Method.java:511)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
05-12 02:49:44.563: E/AndroidRuntime(19288):    at dalvik.system.NativeStart.main(Native Method)

这就是我应该通过服务器返回和处理的内容

["Categories",[[{"id":"2","name":"Glass Repair"},{"id":"3","name":"Appliance Repair"},{"id":"4","name":"Air Conditioning"},{"id":"5","name":"Community Involvement"},{"id":"6","name":"Electrical"},{"id":"7","name":"Flooring"},{"id":"8","name":"Heating Repair"},{"id":"9","name":"Landscaping"},{"id":"10","name":"Plumbing"},{"id":"11","name":"Remodeling\/Renovation"},{"id":"12","name":"Window Coverings"}]]]
4

2 回答 2

2

http://www.json.org/javadoc/org/json/JSONArray.html

尝试

JSONArray jsonArray = new JSONArray(new String(blah));

代替

JSONObject jsonObj = new JSONObject(new String(blah));

您问题中的 JSON 示例实际上是一个 JSON 数组。

因此,它将是

...
    public JSONObject getJSONfromURL (String url){
        //HTTP call
        try{
            URLConnection connection = new URL(url).openConnection();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 2048 * 16);
            StringBuffer builder = new StringBuffer();
            String line;

            while ((line = reader.readLine()) != null) {
              builder.append(line).append("\n");
            }
            String blah = builder.toString();

            //Parsing string into JSONArray
            JSONArray data = new JSONArray(new String(blah));


            for(int i=0; i < data.length(); i++)
            {
                 object = data.getJSONObject(i);
                 String id = object.getString("id"); 
                 String value = object.getString("name"); 
                 Log.d("Item name: ", value);
            }




            } catch(Exception e){
                Log.e("Http Error","Error in http connection " + e.toString());

            }


        return object;
    }


..

以下是关于您的 JSON 数据发生了什么的一些解释。目前它看起来像:

["Categories",[[{"id":"2","name":"Glass Repair"} ....

JSONObject jsonObj = new JSONObject(new String(blah));
JSONArray data = jsonObj.getJSONArray("Categories");

不起作用,因为这个 JSON 数据中没有名为“Categories”的对象,而是有一个值为“Categories”的 String 元素。

您真正应该做的是将您的 JSON 表示形式改成

 {"Categories":[{"id":"2","name":"Glass Repair"} .... }

因此解析器可以找出名为“类别”的 JSON 对象。

这是关于编写 JSON 语法的推荐读物。

http://en.wikipedia.org/wiki/JSON

另外,这里有一个 JSON 验证工具,可以快速调试/纠正 JSON 语法

http://jsonlint.com/
于 2013-05-12T07:00:35.177 回答
0

你必须考虑两件事:

  1. json 响应对应于JSONArraynot JSONObject
  2. 您的 json 响应中的"Categories"条目不是JSONArray您响应的格式。

你应该试试这个。

JSONObject rawJson = new JSONObject ( jsonResponse );
JSONArray categories = rawJson.getJSONArray( "Categories" );

使用这种 json 格式

{"Categories":[{"id":"2","name":"Glass Repair"},{"id":"3","name":"Appliance Repair"},{"id":"4","name":"Air Conditioning"},{"id":"5","name":"Community Involvement"},{"id":"6","name":"Electrical"},{"id":"7","name":"Flooring"},{"id":"8","name":"Heating Repair"},{"id":"9","name":"Landscaping"},{"id":"10","name":"Plumbing"},{"id":"11","name":"Remodeling\/Renovation"},{"id":"12","name":"Window Coverings"}]}
于 2013-05-12T07:14:40.090 回答