2011-07-11 63 views
2

发送Rails中JSON对象这是一个非常简单的问题,我想弥补我知识的空白。通过邮政

很简单的应用程序的工作如下: 1:I:web应用程序创建值 1的散列:II:打开该散列成JSON 1:III:通过POST 这发出跨越到另一个应用程序的JSON是最主要的问题

2:I:其他网络应用程序接收JSON,解串并变回成一个对象。

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

对于1我有我和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}) 

但是我在茫然,如何在通过邮局发送的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?

有没有行业标准,当涉及到的数据作出反应,而不是在响应浏览器

回答

2

你想用from_json这确实的to_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' 
     } 
+0

JSON通常从JavaScript发送。例如见代码。 – s84

+0

好吧,我想我会得到你的上面的代码。但是你是否在说它不应该或者不能用ruby或rails来发送。对不起,我没有定义如何发布。说实话我并不确定。目前没有任何形式,并且在我看来很简单,我可以硬编码一个json并将其发送给其他应用程序。我读过一个表格,需要休息后在HTML,但到现在为止我刚刚被使用NET:HTTP代码和它的工作很好。接受的网络应用程序没有问题,如问题2中所述。 – OVERTONE