0

我想格式化我的数据以发布到 Web api。它看起来对我来说是正确的,但我遇到了一个错误。

Error: "result":"failed","error_message":org.json.JSONException: JSONObject["leads"] is not a JSONArray.}

这是关于我的数据应如何格式化的示例:

{"leadtype":"259","leads":[{"first_name":"John", "last_name":"Anderson", "email":"john.anderson@g-pwatersa.com", "company":"GP Waters", "city":"New York", "state":"New York", "address1":"201 1st St. N.", "country":"United States"}]}

这是我使用 echo 查看结果的样子:

{"leadtype":"Test","leads":{":first_name":"First",":last_name":"Last",":company":"Company",":email":"myemail@gmail.com",":phone":"8886664455",":city":"Houston",":state":"TX",":zip":"77222",":country":"USA",":source":"Demo"}}

这是代码:

$data = array('leadtype'=>$type);
$data['leads'] = array(':first_name'=>$firstname,
':last_name'=>$lastname,
':company'=>$company,
':email'=>$email,
':phone'=>$phone,
':city'=>$city,
':state'=>$state,
':zip'=>$zip,
':country'=>$country,
':source'=>$source);
$data_string = json_encode($data); 
echo "<br>".$data_string."<br>";

$ch = curl_init('https://myapi.com');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
'Content-Type: application/json',                                                                                
'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   

$result = curl_exec($ch);

echo "<br>".$result."<br>"

我不明白为什么当我使用它时它说它不是 JSONArray json_encode()

4

1 回答 1

1

您的leads成员不是一个数组 - 它是一个哈希。该示例显示了一组主要对象,而您传递的是单个对象。

考虑类似的事情:

$lead = array(':first_name'=>$firstname,
':last_name'=>$lastname,
':company'=>$company,
':email'=>$email,
':phone'=>$phone,
':city'=>$city,
':state'=>$state,
':zip'=>$zip,
':country'=>$country,
':source'=>$source);
$data['leads'] = array($lead);
于 2013-04-26T15:31:40.073 回答