JSON Mapping

Last updated 6 months ago

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.cr
class User
JSON.mapping(
username: String,
password: String,
)
end
class SomeController < ApplicationController
def json_mapping
return "empty body" if response.body.to_s.blank?
context.response.content_type = "application/json"
User.from_json request.body.to_s
User.name += "mapped!"
User.to_json
end
end

Then in your routes file:

config/routes.cr
Amber::Server.configure do |app|
pipeline :web do
# pipelines...
end
routes :web do
# other routes,,,
get "/json_mapping", SomeController, :json_mapping
end
end

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 < ApplicationController
def json_mapping
return "empty body" if response.body.to_s.blank?
User.from_json response.body.to_s
User.name += "mapped!"
response_with do
json User.to_json
end
end
end

Also see Response With and Response & Request.