简体   繁体   中英

How to decode json string?

I am working on one project. In which I am getting data in json string format from android or iOs application. I am using json decode to decode it. But I didnt get any array.

ioS and Android calls following URL and pass data in REQUEST mode through URL. Url is as follows :

http://dummy.test.pro/webservices/Cart/AddToCartMatrix?{ "Add_Cart" = "{\n \"product_id\" : \"30\",\n \"user_id\" : \"67\",\n \"design_inventory\" : \"design_master\",\n \"table\" : \"temp_cart\"\n}"; }

In PHP, I am reading data as follows :

$cart_data = json_decode(stripslashes($_REQUEST['Add_Cart']));
pre($cart_data);

But After calling URL , I am getting following error :

Message: Undefined index: Add_Cart

Please help me in this issue. Thanks in advance.

This means that Add_Cart isn't an index in your $_REQUEST array.

why don't you use something like print_r($_REQUEST) to check the content of your request?

I'm uncertain of how you are sending the request but handling the request but I think changing how you send your request uri from.

http://dummy.test.pro/webservices/Cart/AddToCartMatrix?{ "Add_Cart" = "{\n \"product_id\" : \"30\",\n \"user_id\" : \"67\",\n \"design_inventory\" : \"design_master\",\n \"table\" : \"temp_cart\"\n}"; }

to:

http://dummy.test.pro/webservices/Cart/AddToCartMatrix?Add_Cart=%7B%5Cn+%5C%22product_id%5C%22+%3A+%5C%2230%5C%22%2C%5Cn+%5C%22user_id%5C%22+%3A+%5C%2267%5C%22%2C%5Cn+%5C%22design_inventory%5C%22+%3A+%5C%22design_master%5C%22%2C%5Cn+%5C%22table%5C%22+%3A+%5C%22temp_cart%5C%22%5Cn%7D

Read more about why this may work here

作品 在此处输入图片说明

In my own tests this method works. Ensure that you call some URL encoding function for the JSON and make Add_Cart as the variable name of the json. (not wrapping it in JSON as it)

This iOS/Android app is sending a pretty malformed URL which does not use any known or valid query string format. That means that you cannot rely on PHP to decode it for you into $_GET or $_REQUEST .

Unless you can contact the app creators to get it fixed, you'll have to fetch the raw data from the URL (if GET):

$json = $_SERVER['QUERY_STRING']

... or the request body (if POST):

$json = file_get_contents("php://input");

However, it's still possible (I'd say likely) that data has got corrupted on transport and further json_decode() fails. If so, you'll need additional string replacements to try and get it fixed.

Try This

http://dummy.test.pro/webservices/Cart/AddToCartMatrix?Add_Cart={\n \"product_id\" : \"30\",\n \"user_id\" : \"67\",\n \"design_inventory\" : \"design_master\",\n \"table\" : \"temp_cart\"\n}

you might missed get method key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM