parsing JSON response from url in android
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({
"resu开发者_开发知识库lts":{
"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)
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/
I can see 2 problems:
- You are reading the output per line with
in.readline
. First, try reading the whole output into aString
object, to ensure you have valid JSON to work with. 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");
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;
}
精彩评论