繁体   English   中英

使用 cURL 在 PHP 中发布嵌套数组

[英]Posting a nested array in PHP using cURL

我有一些数据需要发布到一个端点,它是一个嵌套数组,例如:

$contentPostData = array(
            'contents' => array(
                'name' => $comment_text,
                'fingerprint' => $fingerprint,
                'signers' => array(
                    $ownerAuthId
                )
            )
        );

当我尝试:

json_encode($contentPostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

我收到错误:

string(518) "{"timestamp":1578447151168,"message":"Can't read request","details":["JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException

如何格式化 contentPostData 以便它可以正确反序列化?

你提到:

json_encode($contentPostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

但是您是否将编码的 json 分配给$data 我的意思是:你在做什么:

$data = json_encode($contentPostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

我看到您正在调用的网络服务使用com.fasterxml.jackson所以很可能需要 JSON 格式,因此您的序列化应该没问题(如果字段名称和类型匹配)。

我还建议设置标头以通知 webservice 您正在发送一个 json 文件(以防它允许其他格式):

curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json'                                                                     
);

所以:

$data = json_encode($contentPostData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json'                                                                       
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

如果这不起作用,那么很可能:a)您的 JSON 无效(预期结构不同)或 b)Web 服务实际上期望与 JSON 不同的格式(例如,可能是标准的多部分数据)

暂无
暂无

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

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