为什么将JSON数据仅作为第一个字符返回?

时间:2018-08-06 15:27:31

标签: android json httpurlconnection

由于某种原因,此URI的调用结果仅返回“ [”。当我浏览到URL时,它会正确显示所有JSON数据。我收到“ 200”响应,因此这不是由于任何身份验证问题引起的,因为它不需要任何凭据,我只是尝试直接检索和解析JSON数据。

public class QueryManager extends AsyncTask {
    private static final String DEBUG_TAG = "QueryManager";

    @Override
    protected ArrayList<Recipe> doInBackground(Object... params) {
        try {
            return searchIMDB((String) params[0]);
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    protected void onPostExecute(Object result) {
    };

    public ArrayList<Recipe> searchIMDB(String query) throws IOException {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json");
        //create URI
        URL url = new URL(stringBuilder.toString());

        InputStream stream = null;
        try {
            // Establish a connection
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.addRequestProperty("Accept", "application/json");
            conn.setDoInput(true);
            conn.connect();

            int responseCode = conn.getResponseCode();
            Log.d(DEBUG_TAG, "The response code is: " + responseCode + " " + conn.getResponseMessage());

            stream = conn.getInputStream();
            return parseResult(stringify(stream));
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    private ArrayList<Recipe> parseResult(String result) {
        String streamAsString = result;
        ArrayList<Recipe> results = new ArrayList<Recipe>();
        try {
            JSONArray array = new JSONArray(streamAsString);
            //JSONArray array = (JSONArray) jsonObject.get("results");
            for (int i = 0; i < array.length(); i++) {
                JSONObject jsonMovieObject = array.getJSONObject(i);

                Recipe newRecipe = new Recipe();

                newRecipe.name = jsonMovieObject.getString("name");
                newRecipe.id = jsonMovieObject.getInt("id");

                JSONArray ingredients = (JSONArray) jsonMovieObject.get("ingredients");

                for(int j = 0; j < ingredients.length(); j++) {
                    JSONObject ingredientObject = ingredients.getJSONObject(j);
                    Ingredient ingredient = new Ingredient();

                    ingredient.ingredientName = ingredientObject.getString("ingredient");
                    ingredient.quantity = ingredientObject.getDouble("quantity");
                    ingredient.measure = ingredientObject.getString("measure");

                    newRecipe.ingredientList.add(ingredient);
                }

            }
        } catch (JSONException e) {
            System.err.println(e);
            Log.d(DEBUG_TAG, "Error parsing JSON. String was: " + streamAsString);
        }
        return results;
    }

    public String stringify(InputStream stream) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream);
        BufferedReader bufferedReader = new BufferedReader(reader);
        return bufferedReader.readLine();
    }
}

2 个答案:

答案 0 :(得分:2)

您获得的JSON被美化了(即具有换行符和可能的缩进)。
但是,在stringify函数中,您仅读取并返回响应的第一行:

return bufferedReader.readLine();

有关将整个InputStream读到String的可能解决方案的列表,请参见here
例如:

ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
    result.write(buffer, 0, length);
}
return result.toString("UTF-8");

答案 1 :(得分:1)

这类似于我在评论中谈论的内容:

public String stringify(InputStream stream) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream);
    BufferedReader bufferedReader = new BufferedReader(reader);
    StringBuilder results = new StringBuilder();
    try {
        String line;
        while ((line = BufferedReader.readLine()) != null) {
            results.append(line);
            results.append('\n');
        }
    } finally {
        try {
            bufferedReader.close();
        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
        }
    }
    return results.toString();
}