为什么 JSON 数据仅作为第一个字符返回?
Why is JSON data being returned as the first character only?
由于某种原因,调用此 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();
}
}
这与我在评论中所说的类似:
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();
}
您得到的 JSON
已被美化(即有换行符和可能的缩进)。
但是,在您的 stringify
函数中,您只读取 return 响应的第一行:
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");
由于某种原因,调用此 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();
}
}
这与我在评论中所说的类似:
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();
}
您得到的 JSON
已被美化(即有换行符和可能的缩进)。
但是,在您的 stringify
函数中,您只读取 return 响应的第一行:
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");