Home > Article > Backend Development > PHP backend implements json interaction with Android
Some friends around me said that when they used the code in that blog, they would report an error in the following code, and there was an error that builder.toString() could not be converted into a json object. <br>
JSONObject jsonObject = new JSONObject(builder.toString());
<br>And I didn’t make any mistakes when I tried it myself. So I did some checks on the php server-side code built by my friends, and finally found the problem . So I wrote this down, hoping to help the majority of students who have stepped into the same pit
This involves the json_decode function of php. This function is the reason why my friends made mistakes.
Now write the code that I have tested successfully. What I sent to the php server on Android is a jsonObject, {"name": "lala"}, and the corresponding entity name is " userJson", which is the following code
JSONObject jo = new JSONObject();
jo.put("name", "test");
params.add(new BasicNameValuePair("userJson",jo.toString() ));
At this time, my server-side code is
<?php $json_string = $_POST ["userJson"]; $user = json_decode($json_string,true);//这里的true加上就会将android发来的json字符串转化为关联数组
$arr = array( 'user_id' => $user["name"] ); $str = json_encode($arr); echo($str); ?>
At this time, it will not report failure in android Error converting to JSONObject, of course I can also send JSONArray to the server on the server side. That is, [{"name":"lalala"},{}]
In this case, the above PHP code cannot be executed correctly to the last sentence. At this time, we need to The code is modified to
<?php $json_string = $_POST ["userJson"]; $user = json_decode($json_string,true);//这里的true加上就会将android发来的json字符串转化为关联数组 $arr = array( 'user_id' => $user[0]["name"] ); $str = json_encode($arr); echo($str); ?>
Why do we need to modify it like this? The reason is actually very simple. When we add true to the json_decode function, the received $json_string will be converted into an associative array. For example, in the first example, jsonObject will be converted into
array(1){ ["name"]=>String("test") }
, so you can use $user["name"] to read the string "test", and in the second example The result of the conversion is
array(2){ [0]=>array(1){ ["name"]=>String("lala") } [1]=>array(0){} }
<br>
At this time, using $user["name"] will cause an error, and you need to use $user[0]["name"] to read " lala" string
Related recommendations:
When the return value of the controller method is a simple type, how to interact with json? <br>
JSON interaction between jQuery and PHP, how to avoid two-dimensional array
Simple json interaction example between php and html
The above is the detailed content of PHP backend implements json interaction with Android. For more information, please follow other related articles on the PHP Chinese website!