简体   繁体   English

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

[英]Posting a nested array in PHP using cURL

I have some data I need to post to an endpoint which is a nested array like:我有一些数据需要发布到一个端点,它是一个嵌套数组,例如:

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

When I try:当我尝试:

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

I get the error:我收到错误:

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

How do I format the contentPostData so that it can be deserialized correctly?如何格式化 contentPostData 以便它可以正确反序列化?

You mention:你提到:

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

But are you assigning the encoded json to $data ?但是您是否将编码的 json 分配给$data I mean: are you doing:我的意思是:你在做什么:

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

I see that the webservice to which you are calling uses com.fasterxml.jackson so most likely expects JSON format and therefore your serialization should be okay (if field names and types match).我看到您正在调用的网络服务使用com.fasterxml.jackson所以很可能需要 JSON 格式,因此您的序列化应该没问题(如果字段名称和类型匹配)。

I also suggest setting the header to inform that webservice that you are sending a json file (in case it allows other formats):我还建议设置标头以通知 webservice 您正在发送一个 json 文件(以防它允许其他格式):

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

So:所以:

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

If that does not work then most likely: a) your JSON is invalid (different structure is expected) or b) the webservice actually expects a different format than JSON (maybe standard multipart data for example)如果这不起作用,那么很可能:a)您的 JSON 无效(预期结构不同)或 b)Web 服务实际上期望与 JSON 不同的格式(例如,可能是标准的多部分数据)

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

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