使用HTTParty在JSON POST请求中发送数组

时间:2014-08-13 19:23:25

标签: ruby-on-rails ruby json httparty

我尝试使用需要在POST请求正文中发送数组的第三方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: "..."}, ... ] }

2 个答案:

答案 0 :(得分:0)

在Ruby on Rails中使用HTTParty在POST主体中嵌入数组的最简单方法是将请求传递给实例变量(您选择的任何名称都可以满足该实例变量的要求)。

所以我们将有

@mypost = HTTParty.post(url, 
         :body => { 
                    :things => {
                       :id => 1, 
                       :id => 2,
                       :id => 3
                    },
                  }.to_json,
         :headers => { 
                    'Content-Type' => 'application/json',
                    'Authorization' => 'xxxxxxxxxx' 
                    'Accept' => 'application/json'
                    })

以下是HTTParty发布请求的示例

 @myrequest = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
            :body => {
                        :books => {  
                          :name => "#{@book.name}",
                          :author => "#{@book.author}",
                          :description => "#{@book.description}",
                          :category_id => "#{@book.category_id}",
                          :sub_category_id => "#{@book.sub_category_id}"
                        },
                      }.to_json, 
            :headers => { 'Content-Type' => 'application/json', 
                          'Authorization' => '77d22458349303990334xxxxxxxxxx',
                          'Accept' => 'application/json'})

我希望这会有所帮助。

在有帮助的情况下将此答案赞为有用,或在答案下方评论以进一步说明。

答案 1 :(得分:-1)

我对SurveyMonkey API有类似的要求,下面将创建一个带有嵌套哈希数组的params_hash

创建哈希的字段数组

fields = []

i =0

while i < 10 do

fields << {":id#{i}" => "some value #{i}"}

i += 1

end

带有可选splat字段变量的方法

def get_response(survey_id, respondent_ids, *fields )

  params_hash = {}

  params_hash[:survey_id] = "#{survey_id}"

  params_hash[:respondent_ids] = respondent_ids

  params_hash[:fields] = fields

  @result = HTTParty.post("http://"some.address.here",

    #:debug_output => $stdout,

    :headers => {'Authorization' => "bearer #{@access_token.to_s}", 'Content-type' => 'application/json'},

  :body => params_hash.to_json,

  )

end
相关问题