在为帖子创建JSON数组时接收错误“不是JSONArray”

时间:2013-04-26 15:26:33

标签: php json rest

我想将我的数据格式化为发布到网络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>"

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

1 个答案:

答案 0 :(得分: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);