在android中解析来自url的JSON响应

时间:2011-05-03 04:56:41

标签: android json

我遇到的问题是我正在解析JSON响应,但它返回错误:

cannot be converted into JSONArray

可能的解决方案是什么?

我的JSON回复:

BIZRATE.Suggest.callback({
 "results":{
    "status":200,
    "keyword":"iphone",
    "suggestions":[  
       "<b>iphone<\/b>",
       "<b>iphone<\/b> cover",
       "<b>iphone<\/b> 4",
       "<b>iphone<\/b> case",
       "rhinestone <b>iphone<\/b> cases",
       "bling <b>iphone<\/b> case",
       "glitter <b>iphone<\/b> case",
       "<b>iphone<\/b> 3g",
       "purple <b>iphone<\/b> case",
       "<b>iphone<\/b> 4 cases"
      ]
    }
  })

我的代码:

package com.ex.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class test extends Activity {

    /** Called when the activity is first created. */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView lv = (ListView)findViewById(R.id.listView1);

        lv.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));        
    }

    public ArrayList<String> fetchTwitterPublicTimeline()
    {
        ArrayList<String> listItems = new ArrayList<String>();

        try {
            URL twitter = new URL(
                    "http://suggest.bizrate.com/app/search?countryCode=US&numResult=10&callback=BIZRATE.Suggest.callback&keyword=iphone&format=json");
            URLConnection tc = twitter.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    tc.getInputStream()));

            String line;
            while ((line = in.readLine()) != null) {
                JSONArray ja = new JSONArray(line);

                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    System.out.println("value----"+jo.getString("suggestions"));
                    listItems.add(jo.getString("suggestions"));
                }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return listItems;
    }
}

我的错误:

05-03 10:22:44.955: WARN/System.err(427): org.json.JSONException: Value BIZRATE.Suggest.callback( of type java.lang.String cannot be converted to JSONArray
05-03 10:22:44.965: WARN/System.err(427):     at org.json.JSON.typeMismatch(JSON.java:107)
05-03 10:22:44.965: WARN/System.err(427):     at org.json.JSONArray.<init>(JSONArray.java:91)
05-03 10:22:44.974: WARN/System.err(427):     at org.json.JSONArray.<init>(JSONArray.java:103)
05-03 10:22:44.974: WARN/System.err(427):     at com.ex.test.test.fetchTwitterPublicTimeline(test.java:47)
05-03 10:22:44.974: WARN/System.err(427):     at com.ex.test.test.onCreate(test.java:31)
05-03 10:22:44.984: WARN/System.err(427):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-03 10:22:44.984: WARN/System.err(427):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-03 10:22:44.984: WARN/System.err(427):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-03 10:22:44.984: WARN/System.err(427):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-03 10:22:44.984: WARN/System.err(427):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-03 10:22:44.994: WARN/System.err(427):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-03 10:22:44.994: WARN/System.err(427):     at android.os.Looper.loop(Looper.java:123)
05-03 10:22:44.994: WARN/System.err(427):     at android.app.ActivityThread.main(ActivityThread.java:4627)
05-03 10:22:45.004: WARN/System.err(427):     at java.lang.reflect.Method.invokeNative(Native Method)
05-03 10:22:45.004: WARN/System.err(427):     at java.lang.reflect.Method.invoke(Method.java:521)
05-03 10:22:45.004: WARN/System.err(427):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-03 10:22:45.004: WARN/System.err(427):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-03 10:22:45.004: WARN/System.err(427):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:5)

您提到JSON响应如下:

> BIZRATE.Suggest.callback({"results":{"status":200,"keyword":"iphone","suggestions":["iphone<\/b>","iphone<\/b>
> cover","iphone<\/b> 4","iphone<\/b>
> case","rhinestone iphone<\/b>
> cases","bling iphone<\/b>
> case","glitter iphone<\/b>
> case","iphone<\/b> 3g","purple
> iphone<\/b> case","iphone<\/b> 4
> cases"]}})

这不是有效的JSON。你应该切掉第一部分,直到(包括)第一个括号。您还需要删除结束括号。这应该会得到一些有效的JSON。

需要注意的另一件事是如何在html中转义斜杠。根据您使用此数据的方式,您可能不希望它被转义。

以下网站可以帮助您验证您的json: http://www.jsonlint.com/

答案 1 :(得分:2)

我可以看到2个问题:

  1. 您正在使用in.readline读取每行的输出。首先,尝试将整个输出读入String对象,以确保您使用有效的JSON。
  2. 您的结果最初不是JSON数组;它是一个JSON对象。我会按如下方式阅读:

    String myUrlResult = ****
    JSONObject j = jo.getJSONObject("results");
    JSONArray ja =  j.getJSONArray("suggestions");