![](/img/trans.png)
[英]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.