我正在尝试格式化我的数据发布到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()
。
您的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);