在Android Studio中从API检索JSONObject

时间:2017-10-04 01:10:11

标签: java android api android-asynctask

我在检索JSONObject并将其转换为字符串的方法中出错,错误显示“!java.lang.String类型的DOCTYPE无法转换为JSONObject”

public class FindSentimentTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... url) {
        String toReturn= "DID NOT WORK";
        try
        {
            toReturn=getResponseFromHttpUrl(url[0]);

        }catch (Exception e)
        {
            Log.d("ErrorInApp","exception on get Response from HTTP call" + e.getMessage());
            return toReturn;
        }

        return toReturn;
    }

    protected void onPostExecute(String sentimentData) {
        try {
            JSONObject sentimentJSON = new JSONObject(sentimentData);
            ((TextView)findViewById(R.id.output)).setText(sentimentJSON.toString());

            //String testOutput = sentimentJSON.get("docs").toString();
            //((TextView)findViewById(R.id.output)).setText(testOutput.toString());
        } catch (Exception e) {
            Log.d("ErrorInApp","exception in onPostExecute" + e.getMessage());
        }
    }
}

public static String getResponseFromHttpUrl(String url) throws IOException {
    URL theURL = new URL(url);
    HttpURLConnection urlConnection = (HttpURLConnection) theURL.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");

        boolean hasInput = scanner.hasNext();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }
}

更具体地说,错误在这里我检索JSONObject并将其转换为字符串以在TextView中显示

protected void onPostExecute(String sentimentData) {
    try {
        JSONObject sentimentJSON = new JSONObject(sentimentData);
        ((TextView)findViewById(R.id.output)).setText(sentimentJSON.toString());

    } catch (Exception e) {
        Log.d("ErrorInApp","exception in onPostExecute" + e.getMessage());
    }
}

我使用的API是https://developer.nytimes.com/article_search_v2.json

0 个答案:

没有答案