[英]JSON Data is not converting to JSONObject from StringRequest volley
[英]Android : how to return JSONObject from Volley OnRequest StringRequest method
我需要通过将字符串数据的值分配给OnResponse()scpoe之外的另一个方法来传递响应字符串,以便我可以通过调用该方法从中返回JSONObject,但它始终返回null
我需要的只是从Volley stringrequest中获取JSONObject,因为响应是xml“
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">........</string>
这是我的代码
static String data;
private void driverByIdStringRequest(int ID,final Context context){
RequestQueue queue = VolleySingleton.getInstance(context.getApplicationContext()).getRequestQueue();
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url+ID,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
response = response.replaceAll("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
response = response.replaceAll("<string xmlns=\"http://tempuri.org/\">", "");
response = response.replaceAll("</string>", "");
String data = response.substring(40);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error : ", error.toString());
}
});
VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
public JSONObject GetDriverById(int ID,Context context){
driverByIdStringRequest(ID, context);
JSONObject json = JSONObject(data);
return json;
}
最好的可维护方法是首先使用解析器解析XML。
只需按照官方文档上的本教程进行即可。
拿到琴弦后,您只需要做
JSONObject mainObject = new JSONObject(Your_Sring_data);
(Android Studio会提示您围绕JSON创建进行正确的尝试/捕获。)
如果来自StringRequest的String响应始终具有以下格式:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">........</string>
其中........
是要获取的JSONObject
,我建议您按照以下方式处理String响应:
...
String jsonString = stringResponse;
jsonString = jsonString.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>"," ");
jsonString = jsonString.replace("<string xmlns=\"tempuri.org/\">"," ");
jsonString = jsonString.replace("</string>"," ");
try {
JSONObject jsonObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
...
回到您的代码, data
当然为NULL,因为JSONObject json = JSONObject(data);
在onResponse
的请求内的onResponse
之前调用。 我建议您参考以下问题的答案:
Android:如何使用Volley从方法返回异步JSONObject?
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.