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

发布于 2024-11-04 08:24:36 字数 5192 浏览 0 评论 0原文

我遇到一个问题,我正在解析 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)

I have a problem that I am parsing a JSON response but it returns an error:

cannot be converted into JSONArray

What will be the possible solution for that?

My JSON response:

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"
      ]
    }
  })

My code:

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;
    }
}

My error:

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

死开点丶别碍眼 2024-11-11 08:24:36

您提到 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/

You mention that the JSON response is the following:

> 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"]}})

This is not valid JSON. You should cut off the first part, up to (and including) the first parenthesis. You will also need to remove the ending parenthesis. That should get you some valid JSON.

One more thing to note is how the slashes are escaped in the html. Depending on how you are using this data, you may not want it to be escaped.

The following site can help you to validate your json:
http://www.jsonlint.com/

南薇 2024-11-11 08:24:36

我可以看到两个问题:

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

    字符串 myUrlResult = ****
    JSONObject j = jo.getJSONObject("结果");
    JSONArray ja = j.getJSONArray("建议");
    

I can see 2 problems:

  1. You are reading the output per line with in.readline. First, try reading the whole output into a String object, to ensure you have valid JSON to work with.
  2. Your result is not initially a JSON array; it's a JSON object. I would read it in as follows:

    String myUrlResult = ****
    JSONObject j = jo.getJSONObject("results");
    JSONArray ja =  j.getJSONArray("suggestions");
    
凶凌 2024-11-11 08:24:36
Note: get the response in form of string not in JSON.then use this function.   

/*
 * convert the JSONP (JSON call back function) to JSON.
 * it will split the function name from the string.
 * calculate the length of function +1 (it will include the parenthesis "(" 
   with function name, now terminate the loop.          
 * split the string starting from calculated length and string length -1 (to  remove the ending parenthesis ")".
*/
public static String jsonCallbackToJson(String stringValue){
    String jsonData=null;
    String functionName=null;
    StringTokenizer st = new StringTokenizer(stringValue, "()");
    while (st.hasMoreElements()){
        functionName = st.nextToken();

        break;
        //Log.d("kam","==jsondata=="+jsonData);
    }
    jsonData= stringValue.substring(functionName.length()+1,stringValue.length()-1);
    return jsonData;
}
Note: get the response in form of string not in JSON.then use this function.   

/*
 * convert the JSONP (JSON call back function) to JSON.
 * it will split the function name from the string.
 * calculate the length of function +1 (it will include the parenthesis "(" 
   with function name, now terminate the loop.          
 * split the string starting from calculated length and string length -1 (to  remove the ending parenthesis ")".
*/
public static String jsonCallbackToJson(String stringValue){
    String jsonData=null;
    String functionName=null;
    StringTokenizer st = new StringTokenizer(stringValue, "()");
    while (st.hasMoreElements()){
        functionName = st.nextToken();

        break;
        //Log.d("kam","==jsondata=="+jsonData);
    }
    jsonData= stringValue.substring(functionName.length()+1,stringValue.length()-1);
    return jsonData;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文