php - 如何修复“java.lang.String 类型的值名称无法转换为 JSONObject”
问题描述
我正在使用 Volley 在 Android 中发送 HTTP 请求,但出现此错误:
java.lang.String 无法转换为 JSONObject。
在服务器端,我使用 PHP 脚本从数据库中获取值。
我的安卓代码:
String server_url = "http://192.168.225.40/server/greetings.php";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, server_url,null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
name.setText(response.getString("name"));
email.setText(response.getString("email"));
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(firebaseUser!=null){
if(!firebaseUser.getEmail().isEmpty())
{
email.setText(firebaseUser.getEmail());}
}
error.printStackTrace();
}
}
);
singletonclasshttp.getInstance(getActivity()).addtorequestque(jsonObjectRequest);
我的 PHP 脚本:
?php
$username="root";
$password="";
$host = "localhost";
$dbname = "test";
$con = mysqli_connect($host,$username,$password,$dbname);
$sql = "select * from user where uid =1;";
$result = mysqli_query($con,$sql);
$data=array();
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_assoc($result);
echo json_encode(array("name"=>$row["name"],"email"=>$row["email"],"type"=>$row["type"]));
}
?>
我需要解析 JSON 并设置文本字段的值。
解决方案
您正在获取 JsonArray。你应该使用StringRequest
. 然后将 String 转换为 JsonArray 并从数组中获取 JsonObject。
推荐阅读
- java - 我应该在 Platform.runLater() 中进行哪些操作?
- java - 如何使用 Intellij 在 Java 中解决 fileNotFoundException
- r - 我可以使用 Grep 或 Grepl 在文本中同时返回两个大写字母的实例吗?
- r - 列名变量的“enquo”不适用于“dplyr::filter”
- sqlite - SQLite3:如何导入 CSV 并更改列类型?
- python - 解析XML:Python ElementTree,查找元素及其父元素,而不是同一父元素中的其他元素
- python - Python中的Vigenere密码不适用于大写/小写字母转换
- java - 在另一个 @Configuration 类中使用 @Configuration Bean 的最佳实践
- r - 字符串中的第一个数字用“*”分隔字符串
- google-colaboratory - 我们如何将存储库从 Google Colaboratory 推送到 Github