Java - 解析 json 对象(输入结束于...的字符 0)

Java - Parsing json object (end of input at character 0 of ...)

我试图简单地获取和解析一些 json,然后将其添加到微调器中。我只需要名称,部分进入第一个微调器,然后当用户选择时将列出该 Json 对象中的主题。

但是,将 json 传递给对象 'unexpected JSON exception org.json.JSONException: End of input at character 0 of' 时,我总是遇到错误。

下面是我当前的代码:

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

    new HttpAsyncTask().execute("http://example.org");
}

public static String GET(String url)
{
    InputStream inputStream = null;
    String result = "";
    try {
        // create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // make GET request to the given URL
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // convert inputstream to string
        if(inputStream != null) {
            result = convertInputStreamToString(inputStream);
        }
        else {
            result = "Did not work!";
        }

    }
    catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException
{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null) {
        result += line;
    }

    inputStream.close();
    return result;
}

public boolean isConnected()
{
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    else {
        return false;
    }
}

private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... urls) {
        return GET(urls[0]);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result)
    {
        try {
            JSONObject jObject = new JSONObject(result);
            //qualifications = jObject.getJSONArray("name");
            bindSpinners();
        }
        catch(JSONException e) {
            Log.e("JSON", "unexpected JSON exception", e);
        }
    }
}

private void bindSpinners() {
    // I will pass the JObject data here to be used to bind to the relevent spinners
}

您正在尝试将 JSONArray 解析为 JSONObject。

尝试

JSONArray jsonArray = new JSONArray(result);

而不是

JSONObject jObject = new JSONObject(result);  

0 of 输入结束,因为您得到的是空响应。在空响应的情况下,您正试图将其转换为 json 对象。