This is a pretty straightforward question and I’m trying to bridge the gaps in my knowledge.
Quite simply the applications work as follows:
1: i: web app creates a hash of values
1: ii: Turns this hash into JSON
1: iii: Sends the JSON across to another application via POST
THIS IS THE MAIN QUESTION
2: i: other web app receives the JSON, deserializes and turns back into an object.
@hostURL = 'http://127.0.0.1:20000/sendJson'
For 1 I’ve got i and ii done. Not too difficult.
@myHash = HASH.new
@myHash =
{
"myString" => 'testestestes'
"myInteger" => 20
}
@myJsonHash = @myHas.to_json
Sending a post request in my application looks like this:
res = Net::HTTP.post_form(URI.parse(@hostURL),
{'myString'=>'testestestest, 'myInteger' => 20})
However I’m at a loss as to how to send the JSON hash across through post.
As for 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"
Would this suffice as I hear Rails automatically deserializes on receiving a request.
On a side note: What should the response be?
These are 2 web apps communicating so returning some html would be bad. Possibly a numeric response? 200? 404?
Are there any industry standards when it comes to responding with data rather than responding to a browser
You want to use
from_jsonwhich does the opposite ofto_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.In terms of sending JSON (server side) to a controller that is usually done from JavaScript or AS3.
You should explain how you are posting. From a form, from a link. That matters; however, the easiest way is to use jQuery.
Here you want the
urlto be the post url such has app.com/posts (your domain, and then a controller) and then the data should be in JSON format, for example: