【发布时间】:2014-10-07 07:16:35
【问题描述】:
我正在尝试使用需要在 POST 请求正文中发送数组的第 3 方 API。我已经掌握了发送 JSON 的窍门;我读过你只需要设置一些标题并在 POST 正文上调用 to_json。但是,我不确定如何在该 POST 正文中嵌入一个数组。我尝试了以下方法:
HTTParty.post(url,
:body => {
:things => [{:id => 1}, {:id => 2}, {:id => 3}],
}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
)
但这给了我一个服务器错误,让我相信数组的格式不正确。有人可以建议如何在 JSON POST 请求中发送数组吗?谢谢!
编辑:
我得到的错误如下:
#<HTTParty::Response:0x10 parsed_response=nil,
@response=#<Net::HTTPInternalServerError 500 Internal Server Error readbody=true>,
@headers={"error_message"=>["Can not deserialize instance of java.lang.Long out of
START_OBJECT token at [Source: org.apache.catalina.connector.CoyoteInputStream@30edd11c;
line: 1, column: 15] (through reference chain: REDACTED[\"things\"])"],
"error_code"=>["0"], "content-length"=>["0"],
"date"=>["Wed, 13 Aug 2014 22:53:49 GMT"], "connection"=>["close"]}>
JSON 格式应为:
{ "things" : [ {"id": "..."}, {"id: "..."}, ... ] }
【问题讨论】:
-
您的代码在我看来总体上没问题。 JSON 将是有效的(并且将包含一个数组),但您可能没有以 API 的正确结构发送数据。您能否提供参考或来自 API 文档的正确示例 JSON?另外,如果相关,请提供服务器错误消息。
-
我已经按照您的要求更新了帖子!还稍微更改了我的代码,因为我第一次犯了错误。
-
密钥
:myid是故意的和必需的吗?它与您的示例 JSON 不匹配。 -
我的错,这是一个错字。但与问题无关。
-
这个 SO answer 可能会有所帮助。看起来
HTTParty默认使用HashConversions来规范化请求。尝试使用HTTParty.query_string_normalizer覆盖数组的这种行为。
标签: ruby-on-rails ruby json httparty