简体   繁体   English

解码laravel 4输入:: json()

[英]Decode laravel 4 Input::json()

I am having a hard time decoding json input in laravel .. am building a Restful API and when i send post data using RestClient and then die and dump in laravel i got 我很难在laravel中解码json输入..正在构建一个Restful API,当我使用RestClient发送帖子数据然后死掉并在laravel中转储我得到了

object(Symfony\Component\HttpFoundation\ParameterBag)#205 (1) {
  ["parameters":protected]=>
  array(6) {
    ["firstName"]=>
    string(8) "John"
    ["lastName"]=>
    string(7) "Doe"
    ["bloodGroup"]=>
    string(2) "B+"
    ["phone"]=>
    string(8) "+9999999"
    ["address"]=>
    string(8) "Somecity"
    ["symptoms"]=>
    string(3) "Bla"
  }
}

Now i have tied to access the data using 现在我已经绑定了使用的数据访问

$data = Input::json();
echo $data->firstName;

that does not work .. tried to convert it to array and then access like $data['firstName'] does not work . 这不起作用..试图将其转换为数组然后访问像$data['firstName']不起作用。

array(1) {
  ["*parameters"] =>
  array(6) {
    ["firstName"]=>
    string(8) "John"
    ["lastName"]=>
    string(7) "Doe"
    ["bloodGroup"]=>
    string(2) "B+"
    ["phone"]=>
    string(8) "+9999999"
    ["address"]=>
    string(8) "Somecity"
    ["symptoms"]=>
    string(3) "Bla"
  }
}

i want to decode the data then save it to db, Here is a tutorial building similar App .. 我想解码数据,然后将其保存到db,这是一个类似App的教程..

I have tried the post_index() method explained here but no luck . 我试过这里解释的post_index()方法,但没有运气。

http://maxoffsky.com/maxoffsky-blog/building-restful-api-in-laravel-part-2-design-api-controller/ http://maxoffsky.com/maxoffsky-blog/building-restful-api-in-laravel-part-2-design-api-controller/

You can use ->get() to access properties from a Symfony\\Component\\HttpFoundation\\ParameterBag response. 您可以使用->get()Symfony\\Component\\HttpFoundation\\ParameterBag响应中访问属性。

$input = Input::json();
$input->get('firstName')

You can also get all inputs as an array and then type cast it to an object with (object) . 您还可以将所有输入作为数组获取,然后使用(object)将其强制转换为对象。 Note that this will throw an error if your property doesn't exists, so if I where you, I would use the ->get() method mentioned above. 请注意,如果您的属性不存在,这将抛出错误,所以如果我在哪里,我会使用上面提到的->get()方法。

$input = (object)Input::all();
$input->firstName;

Based on my experiment 根据我的实验

If you are sending an array of multiple objects like the following example from the Javascript using JSON 如果您使用JSON从Javascript发送多个对象的数组,如以下示例

[{crop_id: 1, test_id: 6},{crop_id: 1, test_id: 7},{crop_id: 1, test_id: 8}]

You need to use Input::json()->all() function in PHP. 你需要在PHP中使用Input :: json() - > all()函数。

$arr = Input::json()->all();
$crop_id = $arr[0]['crop_id'];
$test_id = $arr[0]['test_id'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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