这是一个非常简单的问题,我正在努力弥补我的知识差距。
很简单,应用程序的工作方式如下: 1: i: 网络应用程序创建值的散列 1: ii: 将这个散列转换成 JSON 1: iii: 通过 POST 将 JSON 发送到另一个应用程序 这是主要问题
2: i: 其他网络应用程序接收 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})
但是我不知道如何通过邮寄发送 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 个网络应用程序通信,因此返回一些 html 是不好的。可能是数字响应? 200? 404?
在响应数据而不是响应浏览器方面是否有任何行业标准
最佳答案
您想使用 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 完成的 Controller 方面。
您应该解释您的发帖方式。从表单,从链接。那很重要;然而,最简单的方法是使用 jQuery。
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: json
});
在这里,您希望 url
成为具有 app.com/posts(您的域,然后是 Controller )的帖子 url,然后数据应为 JSON 格式,例如:
data = {
"name" => 'Hello'
}
关于ruby-on-rails - 通过 Post 在 Rails 中发送 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6649158/