Android JSON解析“JSONException; Value

时间:2013-04-30 22:42:58

标签: java android json parsing getjson

我尝试使用下面的代码来解析JSON数据,该网站需要一个API密钥,现在将其作为字符串存储在strings.xml中。

public class JSONParser {

static InputStream is = null;
static JSONArray jarray = null;
static String json = "";

// constructor
public JSONParser() {
}

public JSONArray getJSONFromUrl(String url) {
    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        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, "iso-8859-1"), 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 {

        JSONObject jObj = new JSONObject(json);
        jarray = jObj.getJSONArray("systems");
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jarray;
}
}

MainActivity。

 public class MainActivity extends ListActivity {
private Context context;
private static String url = "https://api.company.com/api/systems";

private static final String TAG_SYSTEM = "systems";
private static final String TAG_SYSTEM_ID = "system_id";

ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

ListView lv ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog dialog;

    private ListActivity activity;

    // private List<Message> messages;
    public ProgressTask(ListActivity activity) {
        this.activity = activity;
        context = activity;
        dialog = new ProgressDialog(context);
    }

    /** progress dialog to show user that the backup is processing. */
    private Context context;

    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        ListAdapter adapter = new SimpleAdapter(context, jsonlist,          
        R.layout.list_item, new String[] { TAG_SYSTEM, TAG_SYSTEM_ID
                 }, new int[] {
                R.id.vehicleType, R.id.vehicleColor });

        setListAdapter(adapter);
        // selecting single ListView item
         lv = getListView();
    }
    protected Boolean doInBackground(final String... args) {

        JSONParser jParser = new JSONParser();
        //Using APIKEY from strings.xml
        String apikey = getString(R.string.apikey);
        // getting JSON string from URL
        JSONArray json = jParser.getJSONFromUrl(url + "&key=" + apikey);

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

            try {
                JSONObject c = json.getJSONObject(i);

                String vcolor = c.getString(TAG_SYSTEM_ID);

                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_SYSTEM_ID, vcolor);
                jsonlist.add(map);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}

}

这是我当前的LogCat

  04-30 15:39:53.775: E/JSON Parser(9814): Error parsing data org.json.JSONException: Value   <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
04-30 15:39:53.780: E/AndroidRuntime(9814): FATAL EXCEPTION: AsyncTask #1
04-30 15:39:53.780: E/AndroidRuntime(9814): java.lang.RuntimeException: An error occured while executing doInBackground()
04-30 15:39:53.780: E/AndroidRuntime(9814):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.lang.Thread.run(Thread.java:856)
04-30 15:39:53.780: E/AndroidRuntime(9814): Caused by: java.lang.NullPointerException
04-30 15:39:53.780: E/AndroidRuntime(9814):     at com.jitesh.androidjsonparser.MainActivity$ProgressTask.doInBackground(MainActivity.java:102)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at com.jitesh.androidjsonparser.MainActivity$ProgressTask.doInBackground(MainActivity.java:1)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-30 15:39:53.780: E/AndroidRuntime(9814):     ... 5 more
04-30 15:40:03.035: E/WindowManager(9814): Activity com.jitesh.androidjsonparser.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4257ae80 that was originally added here
04-30 15:40:03.035: E/WindowManager(9814): android.view.WindowLeaked: Activity com.jitesh.androidjsonparser.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4257ae80 that was originally added here
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:402)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.Window$LocalWindowManager.addView(Window.java:554)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.Dialog.show(Dialog.java:277)
04-30 15:40:03.035: E/WindowManager(9814):  at com.jitesh.androidjsonparser.MainActivity$ProgressTask.onPreExecute(MainActivity.java:69)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.AsyncTask.execute(AsyncTask.java:534)
04-30 15:40:03.035: E/WindowManager(9814):  at com.jitesh.androidjsonparser.MainActivity.onCreate(MainActivity.java:47)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.Activity.performCreate(Activity.java:5206)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.access$600(ActivityThread.java:140)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.Looper.loop(Looper.java:137)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.main(ActivityThread.java:4898)
04-30 15:40:03.035: E/WindowManager(9814):  at java.lang.reflect.Method.invokeNative(Native Method)
04-30 15:40:03.035: E/WindowManager(9814):  at java.lang.reflect.Method.invoke(Method.java:511)
04-30 15:40:03.035: E/WindowManager(9814):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
04-30 15:40:03.035: E/WindowManager(9814):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
04-30 15:40:03.035: E/WindowManager(9814):  at dalvik.system.NativeStart.main(Native Method)

有人可以帮我解决这些问题。如果您花时间阅读和帮助,请提前感谢您。

2 个答案:

答案 0 :(得分:0)

该服务显然会返回服务器错误。尝试从可以看到响应的客户端调用具有相同参数的服务,或者在尝试将其解析为JSON之前记录String响应。确切的服务器响应肯定会告诉您查询有什么问题。

答案 1 :(得分:0)

您的服务器出错。您想检查状态代码 通过调用httpResponse.getStatusLine()。getStatusCode()

如果状态代码为200,则可以开始解析结果。否则,这是一个错误,你必须优雅地处理错误。