JSON Mapping
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
1
class User
2
JSON.mapping(
3
username: String,
4
password: String,
5
)
6
end
7
8
class SomeController < ApplicationController
9
def json_mapping
10
return "empty body" if request.body.to_s.blank?
11
context.response.content_type = "application/json"
12
user = User.from_json request.body.to_s
13
user.username += "mapped!"
14
user.to_json
15
end
16
end
Copied!
Then in your routes file:
config/routes.cr
1
Amber::Server.configure do |app|
2
pipeline :web do
3
# pipelines...
4
end
5
6
routes :web do
7
# other routes,,,
8
get "/json_mapping", SomeController, :json_mapping
9
end
10
end
Copied!
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
1
class SomeController < ApplicationController
2
def json_mapping
3
return "empty body" if request.body.to_s.blank?
4
user = User.from_json request.body.to_s
5
user.username += "mapped!"
6
response_with do
7
json user.to_json
8
end
9
end
10
end
Copied!
Last modified 2yr ago
Copy link