本文介绍了如何修复“类型java.lang.String的值名称无法转换为JSONObject"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Volley在Android中发送HTTP请求,但出现此错误:
I'm am using Volley to send an HTTP request in Android and I'm getting this error:
在服务器端,我使用PHP脚本从数据库中获取值.
On the server side, I use a PHP script to get values from the database.
我的Android代码:
My Android code:
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并设置文本字段的值.
I need to parse the JSON and set the value for the text fields.
推荐答案
您正在获取JsonArray.您应该使用StringRequest
.然后将String转换为JsonArray并从数组中获取JsonObject.
You are getting JsonArray. You should use StringRequest
. Then convert String to JsonArray and get JsonObject from the array.
这篇关于如何修复“类型java.lang.String的值名称无法转换为JSONObject"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!