【问题标题】:Why is JSON data being returned as the first character only?为什么 JSON 数据仅作为第一个字符返回?
【发布时间】:2019-01-13 14:42:08
【问题描述】:

由于某种原因,仅返回“[”作为此 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();
    }
}

【问题讨论】:

  • 您的stringify 函数看起来只返回bufferedReader 的第一行。您是否尝试过遍历所有行?

标签: android json httpurlconnection


【解决方案1】:

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

return bufferedReader.readLine();

请参阅here 以获取将整个InputStream 读取为String 的可能解决方案列表。
例如:

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");

【讨论】:

    【解决方案2】:

    这与我在 cmets 中所说的类似:

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-02
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      • 2017-03-13
      • 1970-01-01
      • 2020-04-08
      • 2019-03-08
      相关资源
      最近更新 更多