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

问题描述 投票:1回答:2

我正在尝试使用第三方API,该API需要在POST请求正文中发送数组。我已经掌握了发送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: "..."}, ... ] }
ruby-on-rails ruby json httparty
2个回答
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 Post Request的示例

 @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
投票

我对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
© www.soinside.com 2019 - 2024. All rights reserved.