解码这个json的正确方法是什么?
我的型号有
protected $casts = [
'items' => 'array'
];
我的json项目:
{
"data": [
{
"name": "Google",
"link": "http://google.com"
},
{
"name": "ALink",
"link": "http://link.org"
}
]
}
json_decode($request->items)
返回错误:ErrorException: Object of class stdClass could not be converted to string in file
json是一个对象,而不是数组。你应该把它投射到像这样的物体上
protected $casts = [
'items' => 'object'
];
要将json保存到您的模型中,您可以在如上所述将强制转换为对象后执行$obj->items = $request->items
。
或者,如果必须将其保存为一个数组,则可以通过执行(array)$request->items
而不是json_decode将请求强制转换为一个。