美好的一天,我有一组JSONObject值,我从服务器收到并操作.大多数情况下,我得到一个带有值的JSONObject(比方说统计),有时,它会返回一个带有代码和错误描述的Error对象.现在我的问题是我如何构造我的代码,以便它在返回错误时不会中断.我以为我可以做到这一点,但不起作用.任何帮助将受到高度赞赏.谢谢
public void processResult(JSONObject result) {
try {
if(result.getJSONObject(ERROR) != null ){
JSONObject error = result.getJSONObject(ERROR);
String error_detail = error.getString(DESCRIPTION);
if(!error_detail.equals(null)) {
//show error login here
}
finish();
}
else {
JSONObject info = result.getJSONObject(STATISTICS);
String stats = info.getString("production Stats"));
}
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用我的应用程序中Volley提出POST请求,在我的情况下,一个很好的响应是一个201空洞的身体.我正在使用JSONRequest,拨打电话.
我的问题是错误响应处理程序被调用,因为响应为空.
以下是我的要求:
Request request = new JsonRequest<Object>(Request.Method.POST, url, body, new Response.Listener<Object>() {
@Override
public void onResponse(Object response) {
}
}, new ErrorListener(context)) {
@Override
protected Response<Object> parseNetworkResponse(NetworkResponse response) {
Log.d(TAG, "success!!!!!!");
if (response.statusCode == 201)
mListener.resetPasswordWasSent();
return null;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/json");
params.put("Accept", "application/json");
return params;
}
};
requestQueue.add(request);
Run Code Online (Sandbox Code Playgroud)
我的parseNetworkResponse函数获取调用,那么ErrorListener,和onResponse因为我得到一个方法永远不会命中NullPointerException的ErrorListener …
这是我关于StackOverflow的第一个问题,很抱歉这个问题表达不好.
以下是logcat中的Json:
I/Result is: null{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
public class MainActivity extends AppCompatActivity {
String weather,id,result;
public class DownloadTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while(data != -1){
char count = (char) data;
result += count;
data = inputStreamReader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) { …Run Code Online (Sandbox Code Playgroud)