有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在Android Studio中从API检索JSONObject

检索JSONObject并将其转换为字符串的方法中出现错误,错误为“!DOCTYPE of type java.lang.string无法转换为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) 个答案