java - Android 中 JSONObject 与 JSONArray 的问题
问题描述
我猜我有一个非常具体的问题。我正在使用 Volley 库从 URL 获取字符串响应,响应如下:
{"email":"imribar@gmail.com","phone":"7(707)111-11-11","family_name":"Жилин","name":"Иван","role":0}
我通过在 PHP 中将我的 SQL 查询数组转换为 JSON 来得到这个响应
$output=$db->query("SELECT email, phone, family_name, name, role FROM users WHERE email=?", "$email")->fetchArray();
$json=json_encode($output, JSON_UNESCAPED_UNICODE);
echo"$json";
接下来我需要做的是通过这个 JSON 并将记录插入到我的 Android APP 中的本地数据库中。为此,我执行以下操作:
if(response.contains("email")) {
testResponse.setText("Response is2: " + response);
try {
JSONArray jsonArr = new JSONArray(response);
for(int i=0; i < jsonArr.length();i++){
JSONObject jsonObj = jsonArr.getJSONObject(i);
Log.i("User",jsonObj.toString());
User user = new User();
user.email= jsonObj.getString("email");
user.phone=jsonObj.getString("phone");
user.firstName=jsonObj.getString("name");
user.lastName=jsonObj.getString("family_name");
user.role=jsonObj.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
}
} catch (JSONException e) {
Log.i("JSONerror", e.toString());
}
}
我不断收到以下错误:
13:24:59.518 22389-22389/com.local.school I/JSONerror: org.json.JSONException: Value {"email":"imribar@gmail.com","phone":"7(707)111-11-11","family_name":"Жилин","name":"Иван","role":0} of type org.json.JSONObject cannot be converted to JSONArray
知道我可以在 PHP 端做什么来更改 JSONString(添加 [],或向数组添加名称),或者我需要在 Android 中做什么?
解决方案
我建议您在调用应用程序时使用 aJsonObjectRequest
而不是。它与 StringRequest 几乎相同,但它得到了一个答案。StringRequest
Volley
JSONObject
String url = "http://my-json-feed";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// your cose goes here:
JSONObject jsonObject = new JSONObject(response.toString());
User user = new User();
user.email= jsonObject.getString("email");
user.phone=jsonObject.getString("phone");
user.firstName=jsonObject.getString("name");
user.lastName=jsonObject.getString("family_name");
user.role=jsonObject.getInt("role");
user.token="123123123fsadf";
insertUser inewuser = new insertUser();
inewuser.execute(user);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
推荐阅读
- sql - 有没有办法在SQL中找到超过n天的最新日期?
- c# - 如何将自定义异常放入 Try-Catch-Finally 但在 Winforms 中同时使用 If 条件?
- android - SwipeRefreshLayout 尝试在空对象引用上调用虚拟方法
- reactjs - 在运行时与上下文状态共享 React Web 组件状态
- android - 当用户点击其他应用程序时如何得到通知
- python - 如何让 Discord Bot 说出消息的作者
- excel - 我们可以使用VBA excel提取pdf中当前选定文本的坐标吗
- asp.net-mvc-5 - 未能渲染 squishit bundal
- caching - 此代码生成多少缓存命中和缓存未命中?
- javascript - 可排序和可过滤在 DataTable vuetify 中来自 api 的动态数据中不起作用