开发者

How can i connect to a separate server and parse its JSON response?

i need to connect to another server we manage 开发者_运维问答and have it's results (in JSON format) processed by rails... how can I do it ?

Thanks!


With the NET/HTTP library, you can get the content of a distant file.
Then with the JSON library you can parse a json string into a hash.

def get_datas
    url = URI.parse("http://www.example.com/page.json")
    res = Net::HTTP.start(url.host, url.port) {|http|
        http.get(url.path)
    }
    JSON.parse res.body
end


You can use something like ActiveResource as a model if you like that kind of interface:

class Thing < ActiveResource::Base
  self.site = "http://api.example.com:3000/"
  self.format = :json
  self.element_name = "thing"
end

This might be more than you need, though, as often Net::HTTP and the JSON library will do the job.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜