android - 为什么我无法转换我的服务器响应并出现错误?
问题描述
我从网络服务器接收一些数据。它只有两个部分,名称和 ID。不知道为什么它不工作尝试使用 jsonarray 和 json 对象,但都没有工作。我收到了响应,但无法将其转换为我可以在程序的其他部分使用响应的数据设置。不知道我做错了什么。
我的回复代码:
try {
Data User = new Data();
JSONObject UserName= new JSONObject();
JSONObject user = (UserName.getJSONObject(res));
User.setUserID(user.getInt("UserID"));
User.setUserName(user.getString("UserName"));
} catch (JSONException e) {
e.printStackTrace();
}
}
// System.out.println(getResponse);
@Override
protected String doInBackground(Void... v) {
HashMap<String, String> params = new HashMap<>();
params.put(Config.KEY_UserEmail, UserEMail);
params.put(Config.KEY_Userloggedstatus, Loggedstatus);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Config.URL_ADDACCOUNTLOGIN, params);
Log.d(TAG, "doInBackground: "+ params);
Log.d(TAG, "doInBackground: SENDED!");
Log.d(TAG, "doInBackground: "+ res);
return res;
}
那是我的服务器响应:
doInBackground: {"UserName":"Felix","UserID":6}
这就是错误:
org.json.JSONException: Value {"UserName":"Felix","UserID":6} of type org.json.JSONObject cannot be converted to JSONArray
上次也是:
org.json.JSONException: No value for Result
我应该如何更改我的代码以正确接收它并可以使用响应?
解决方案
试试这个。为我工作。
try {
String res = "{\"UserName\":\"Felix\",\"UserID\":6}";
Data User = new Data();
org.json.JSONObject user = new JSONObject(res);
User.setUserID(user.getInt("UserID"));
User.setUserName(user.getString("UserName"));
System.out.println(User.getUserID());
System.out.println(User.getUserName());
} catch (JSONException e) {
e.printStackTrace();
}
推荐阅读
- jquery - 需要帮助来提高使用 canvas2image javascript 的分辨率(应该很容易.. 但我很新)
- reactjs - 如何在 React 和 Flask 中检测过期的 PayPal 订阅?
- r - 如何确定给定值在 R 中的样本中的百分位数
- javascript - 即使我在购物车数组中传递对象,req.session.cart 总是给出未定义的
- python - 如何使用 [] 和 {} 猴子补丁列表和字典创建?
- mysql - 如何编写具有两个左连接和两个计数的 MySql 查询
- php - 获取不带时间戳的数组数据
- sql - 在第一个 where 子句上过滤数据集,然后在第二个 where 子句上过滤剩余的数据集
- python - 我想使用熊猫绘制我的数据框的第一行
- php - 我正在使用 manjaro 并且无法使用 php artisan 迁移它显示找不到 sql 驱动程序