Get JSON response In Codeigniter

2019-04-12 02:46发布

问题:

I am passing the Object from fiddler to the service written in codeigniter. My Object is something look like this :

My Response :

   {
   "GetResponse":{
      "OrgName":"adfasd",
      "OrgAdr1":"asdf",
      "OrgAdr2":"NA",
      "ProductList":[
          {
               "ProductID":8724,
               "Pallets":0,
               "Pieces":0,
               "Description":"sdfsd"
          }
       ]
   }
}

What I want :

I want to save the response as a JSON Object in codeigniter and also want to fetch the JSON Object or Array inside the main Object.

What I tried :

My service method in codeigniter is something like this :

public function Save()
{
     $Data = json_decode(file_get_contents('php://input'));
     echo $Data;
}

But I am getting nothing in Response Body inside Fiddler.

If I use this code :

$Data = file_get_contents('php://input');
echo $Data;

then it is showing me the response but in the form of String. I want to save it as an JSON Object.

Can anyone tell me what am I missing here ?

回答1:

use this code:

header('Content-type: application/json');

$Data = json_decode(file_get_contents('php://input'),true);

now, you will get $Data as a array.

and you get value by $Data['name'].



回答2:

json_decode() parses a json string to a php variable in the form of an object or associative array. json_encode() does the reverse.

I think what is happening is that php://input is already in json format. When you run it through json_decode() you turn it into a php object which when echoed should throw an error like

Object of class stdClass could not be converted to string ....

If error reporting is suppressed the script stopped there and you get nothing echoed.



回答3:

To encode any value into JSON we must use json_encode(). what mistake you have done that you are decoding a non json object. So the result in null.

 public function Save()
    {
         $Data = json_encode(file_get_contents('php://input'));
         echo $Data;
    }


回答4:

json_decode() return either an object or an array ,so your save() should be like this

public function Save()
{
     $Data = json_decode(file_get_contents('php://input'));
     echo '<pre>';
     print_r( $Data);
}

output will be :-

stdClass Object
(
    [GetResponse] => stdClass Object
        (
            [OrgName] => adfasd
            [OrgAdr1] => asdf
            [OrgAdr2] => NA
            [ProductList] => Array
                (
                    [0] => stdClass Object
                        (
                            [ProductID] => 8724
                            [Pallets] => 0
                            [Pieces] => 0
                            [Description] => sdfsd
                        )

                )

        )

)


回答5:

Try this,

public function Save()
{
     $Data = json_decode(file_get_contents('php://input'));
     var_dump($Data);
}