我一直试图从API响应中获取JSONArray。 JSON响应完全有效,我在jsonlint.com上检查了相同的内容。但是当我调用并尝试处理它时,jsonarray返回为空。以下是通过浏览器尝试的API响应:{"IsBlockUser":"0","BlockedByUserId":"","BlockedMessage":"","ChatHistory":[{"UserName":"Ashish Bahl","UserId":"5475","UserImage":"9f0ecf01-7806-4fb4-b814-8ed81f7ff4ea.jpeg","Message":"bancho","ChatReciverType":"User","RecieverId":"4099","CreatedDate":"3/31/2017 11:47:58 AM","PrettyDate":"21 minutes ago"}]}
以下是用于进行API调用的代码:
`public static class PersonalChatTask extends AsyncTask<Void, Void, Void> {
private static final String LOG_TAG = PersonalChatTask.class.getSimpleName();
public PersonalChatTask() {
super();
}
@Override
protected Void doInBackground(Void... voids) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//Will contain the response as a raw JSON string.
String dataString = null;
try {
//Here we construct the url for the movie database query
//http://api.themoviedb.org/3/movie?
//final String QUERY_PARAM = "sort_by";// sorting parameter popularity or rating
Uri builtUri = Uri.parse(BuildConfig.BASE_URL).buildUpon()
.appendPath("Chat_GetChatHistory")
//.appendQueryParameter(QUERY_PARAM,params[0]) //String key , String value
.appendQueryParameter(TOKEN,getUserData().getToken())
.appendQueryParameter(API_KEY,BuildConfig.API_KEY_VALUE)
.appendQueryParameter("RecieverId","4099")
.appendQueryParameter("pageNumber","1")
.build();
URL url = new URL(builtUri.toString());
// Create the request to TheMovieDatabase, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//read the input stream into a string
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
//Do Nothing
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line);
}
if (buffer.length() == 0) {
//Stream was empty.No point in parsing.
return null;
}
dataString = buffer.toString();
getDataFromJSONString(dataString);
} catch (IOException e){
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
Log.e(LOG_TAG, "Error ", e);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return null;
}
private void getDataFromJSONString(String dataString) throws JSONException {
final String DB_CHAT_HISTORY = "ChatHistory";
try {
JSONObject chatJson = new JSONObject(dataString);
JSONArray chatArray = chatJson.getJSONArray(DB_CHAT_HISTORY);
int size = chatArray.length();
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
}`
我使用调试器检查变量 dataString ,这是{"IsBlockUser":"0","BlockedByUserId":"","BlockedMessage":"","ChatHistory":[]}
答案 0 :(得分:0)
如果您确定要获得有效(非空)阵列,可以尝试其他方法......
ObjectMapper mapper = new ObjectMapper();
JsonNode arrayItems = mapper.readTree(dataString).get("DB_CHAT_HISTORY");
JsonArray chatArray = new JsonArray();
for (JsonNode chat : arrayItems)
chatArray.add(chat);