This recipe will help you to setup a basic JSON Mapping in your application.
First you need an amber project generated with Amber CLI or from scratch.
You can use JSON.mapping
to directly create an object from JSON:
src/controllers/some_controller.crclass UserJSON.mapping(username: String,password: String,)end​class SomeController < ApplicationControllerdef json_mappingreturn "empty body" if request.body.to_s.blank?context.response.content_type = "application/json"user = User.from_json request.body.to_suser.username += "mapped!"user.to_jsonendend
Then in your routes file:
config/routes.crAmber::Server.configure do |app|pipeline :web do# pipelines...end​routes :web do# other routes,,,get "/json_mapping", SomeController, :json_mappingendend
Alternatively you can use response_with
helper. Here you don't need to setup content_type
, however the requested path requires a .json
extension, by example /json_mapping.json
class SomeController < ApplicationControllerdef json_mappingreturn "empty body" if request.body.to_s.blank?user = User.from_json request.body.to_suser.username += "mapped!"response_with dojson user.to_jsonendendend
Also see Response With and Response & Request.