我的android应用程序应该使用volley库向api服务器发送jsonobjectrequest。我试了很多次,但凌空一直抛出以下例外:
org.json.jsonexception:值异常!无法将java.lang.string类型的转换为jsonobject
当库的jsonobjectrequest示例接收到响应文本(json字符串)时,似乎已经抛出了这个异常,因此我认为这甚至不意味着问题出在我编写的代码中。我认为图书馆没有正确地解释答案。当然,我试图简单地用webbrowser加载api端点,而服务器只是用格式良好的json字符串进行响应。json非常小,我使用一个json验证器来验证它,这个验证器说它都是有效的。服务器端是用php编写的,我显式地设置了头 'Content-Type: application/json; charset=UTF-8'
同样,我使用webbrowser的开发工具验证了这一点,并且确实,响应中出现了预期的头。
综上所述:
响应中的json字符串有效。
http标头集: Content-Type: application/json; charset=UTF-8
当我使用volley stringrequest从api端点加载数据时,它只返回预期的响应文本(json字符串)。另外,我可以使用jsonobject类显式解析这个json字符串。作为一种解决方法,我可以这样做,但这很麻烦,因为库中有专门的json请求类来完成这些工作(比如 JsonRequest
以及 JsonObjectRequest
).
我在互联网上找到了一些信息,声称与http头文件/编码/字符集有关。首先,我希望volley能够自动检测响应属性,以正确的方式解释它,但是仍然存在一些问题。我尝试在java代码中显式地设置编码和内容类型,尝试在服务器端更改内容类型和编码(从而更改响应)。
api端点返回的json字符串:
{
"data": {
"user_id": "1",
"firstname": "J",
"insertion": null,
"lastname": "S",
"username": "TestUserName",
"email": "test@example.com",
"date_created": "0",
"api_token": "not applicable yet"
}
}
这是我的密码:
String url = "http://www.example.com/api/signin";
RequestQueueSingleton req = RequestQueueSingleton.getInstance(getApplicationContext());
// For if some response data is in cache from previous tests.
req.getRequestQueue().getCache().clear();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if (response.has("error")) { // response JSON object contains property "error"
onUserSignedInReject(response.getString("error"));
}
// In normal signin cases, the response JSON string contains a property "data"
JSONObject data = response.getJSONObject("data");
int userId = data.getInt("user_id");
String fisrtname = data.getString("firstname");
String insertion = data.getString("insertion");
String lastname = data.getString("lastname");
String username = data.getString("username");
String email = data.getString("email");
int dateCreated = data.getInt("date_created");
String apiToken = data.getString("api_token");
onUserSignedIn(userId, fisrtname, insertion, lastname, username, email, dateCreated, apiToken);
} catch (JSONException e) {
Log.d("JSON.Exception", e.getMessage());
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.d("Loading.error", error.getMessage());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("api_key", "test_api_key");
params.put("email", "test@example.com");
params.put("password", "test");
return params;
}
};
req.addToRequestQueue(jsonObjReq);
暂无答案!
目前还没有任何答案,快来回答吧!