Some friends said that they use the code of the blog in the following code error, there is builder.tostring () can not be converted to JSON object errors.
Jsonobject jsonobject = new Jsonobject (builder.tostring ());
and I'm not wrong about my own experiment. So the friend built PHP server-side code for some checks, and finally found the problem lies . So write this down, hoping to help the vast number of students stepping into the same pit
This involves PHP's Json_decode function, which is why my friends are making mistakes.
Now write the code I have tested successfully, I am in the Android sent to the PHP server is a jsonobject,{"name": "Lala"}, the corresponding entity name is "Userjson", that is, the following code
Jsonobject Jo = new Jsonobject ();
Jo.put ("name", "Test");
Params.add (New Basicnamevaluepair ("Userjson", Jo.tostring ()));
At this point, my server-side code is
<?php $json _string = $_post ["Userjson"]; $user = Json_decode ($json _string,true);//True plus converts a JSON string from Android to an associative array
$arr = Array ( ' user_id ' = = $user ["name"] ); $str = Json_encode ($arr); Echo ($STR); ? >
at this time on Android will not be reported can not be converted to Jsonobject error, of course I can also on the server side to send Jsonarray to the server. That is, [{"Name": "Lalala"},{}]
In this case, the above PHP code will not be executed correctly to the last sentence, this time we want to change the code to
<?php $json _string = $_post ["Userjson"]; $user = Json_decode ($json _string,true);//True plus converts the JSON string from Android to an associative array $arr = Array ( ' user_id ' = > $user [0]["name"] ); $str = Json_encode ($arr); Echo ($STR); ? >
Why do you want to change it? The reason is very simple, and when we add true to the Json_decode function, we convert the received $json_string into associative arrays. For example, the first example, Jsonobject will be transformed into a
Array (1) {["Name"]=>string ("Test")}
So you can read the string "test" with $user["name", and the result of conversion in example two is
Array (2) {[0]=>array (1) {["Name"]=>string ("Lala")}[1]=>array (0) {}}
This time using $user["name"] will be wrong, and need to use $user[0]["name"] to read to "Lala" string
Related recommendations:
How can I interact with JSON when the return value of the Controller method is a simple type?
How to avoid two-dimensional arrays of jquery and PHP json interaction
PHP Simple JSON interaction example with HTML