【问题标题】:Sending JSON object in Rails via Post通过 Post 在 Rails 中发送 JSON 对象
【发布时间】:2011-10-02 17:05:14
【问题描述】:

这是一个非常简单的问题,我正在努力弥补我的知识差距。

很简单,应用程序的工作方式如下: 1: i: web app 创建一个哈希值 1:ii:将此哈希转换为 JSON 1:iii:通过 POST 将 JSON 发送到另一个应用程序 这是主要问题

2: i: 其他 web 应用接收 JSON,反序列化并返回对象。

@hostURL = 'http://127.0.0.1:20000/sendJson'

对于 1,我已经完成了 i 和 ii。不太难。

@myHash = HASH.new
    @myHash =
    {
      "myString" => 'testestestes'
      "myInteger" => 20
    }

    @myJsonHash = @myHas.to_json

在我的应用程序中发送发布请求如下所示:

  res = Net::HTTP.post_form(URI.parse(@hostURL),
    {'myString'=>'testestestest, 'myInteger' => 20})

但是我不知道如何通过 post 发送 JSON 哈希。

至于2:

  @request = UserRequest.new({:myString => params[:myString], :myInteger => params[:myInteger] })
           if @request.save
    #ok
      puts "OBJECT CREATED AND SAVED"
    else
    #error
      puts "SOMETHING WENT WRONG WITH OBJECT CREATION"

我听说 Rails 在收到请求时会自动反序列化,这是否足够?


附带说明:响应应该是什么?

这是 2 个 Web 应用程序进行通信,因此返回一些 html 会很糟糕。可能是数字响应? 200? 404?

在响应数据而不是响应浏览器方面是否有任何行业标准

【问题讨论】:

    标签: ruby-on-rails ruby json rest post


    【解决方案1】:

    您想使用与to_json 相反的from_json。这将以 JSON 格式发送的对象并将其转换为 ruby​​,以便您的模型或您保存它的方式能够理解。

    @post = Post.new
    @post.name = "Hello"
    
    #this converts the object to JSON
    @post.to_json 
    
    @post = You want to use `from_json` which does the opposite of `to_json`. This will take the object being sent in JSON and convert it into ruby so your model or however you save it will understand.
    
    
    @post = Post.new
    @post.name = "Hello"
    
    #this converts the object to JSON
    @post.to_json 
    
    @post = {
         "name" => 'Hello'
       }   
    
    #this puts it back into JSON
    @post.from_json
    
    @post.name = "Hello"
    @post.to_json
    

    就发送 JSON(服务器端)到控制器而言,这通常是通过 JavaScript 或 AS3 完成的。

    你应该解释你是如何发帖的。来自表格,来自链接。这很重要;但是,最简单的方法是使用 jQuery。

    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: success,
        dataType: json
    });
    

    在这里,您希望 url 成为具有 app.com/posts (您的域,然后是控制器)的帖子网址,然后数据应为 JSON 格式,例如:

    data = {
             "name" => 'Hello'
           }
    

    【讨论】:

    • JSON 通常从 JavaScript 发送。以代码为例。
    • 好的,我想我得到了你上面的代码。但是您是说它“不应该”或不能使用 ruby​​ 或 rails 发送。很抱歉没有定义我的发帖方式。老实说,我不太确定。目前没有表格,在我看来,这很简单,我可以硬编码一个 json 并将其发送到另一个应用程序。我确实读过 HTML 中的 rest post 需要一个表单,但到目前为止,我一直在使用 NET:HTTP 代码并且它运行良好。接收网络应用程序没有问题 2 中的问题。
    猜你喜欢
    • 2014-05-20
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 2018-10-15
    相关资源
    最近更新 更多