gpt4 book ai didi

java - 安卓 : how to return JSONObject from Volley OnRequest StringRequest method

转载 作者:太空宇宙 更新时间:2023-11-04 13:27:14 25 4
gpt4 key购买 nike

我需要通过将字符串数据的值分配给 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;
}

最佳答案

如果来自 StringRequest 的字符串响应始终具有以下格式:

<?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);在调用的Request中的onResponse之前调用。对于您的问题,建议您引用我在以下问题中的回答:

Android: How to return async JSONObject from method using Volley?

希望这有帮助!

关于java - 安卓 : how to return JSONObject from Volley OnRequest StringRequest method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32520537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com