Binding using Reactive Frameworks

From a developer perspective however, you can generally just work with Plain Old Java Objects (POJOs) and can optionally use a Reactive framework such as RxJava or Project Reactor. The following is an example of a controller that reads and saves an incoming POJO in a non-blocking way from JSON:

Using Reactive Streams to Read the JSON

  1. @Controller("/people")
  2. public class PersonController {
  3. Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>();
  4. @Post("/saveReactive")
  5. @SingleResult
  6. public Publisher<HttpResponse<Person>> save(@Body Publisher<Person> person) { (1)
  7. return Mono.from(person).map(p -> {
  8. inMemoryDatastore.put(p.getFirstName(), p); (2)
  9. return HttpResponse.created(p); (3)
  10. }
  11. );
  12. }
  13. }

Using Reactive Streams to Read the JSON

  1. @Controller("/people")
  2. class PersonController {
  3. Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>()
  4. @Post("/saveReactive")
  5. @SingleResult
  6. Publisher<HttpResponse<Person>> save(@Body Publisher<Person> person) { (1)
  7. Mono.from(person).map({ p ->
  8. inMemoryDatastore.put(p.getFirstName(), p) (2)
  9. HttpResponse.created(p) (3)
  10. })
  11. }
  12. }

Using Reactive Streams to Read the JSON

  1. @Controller("/people")
  2. class PersonController {
  3. internal var inMemoryDatastore: MutableMap<String, Person> = ConcurrentHashMap()
  4. @Post("/saveReactive")
  5. @SingleResult
  6. fun save(@Body person: Publisher<Person>): Publisher<HttpResponse<Person>> { (1)
  7. return Mono.from(person).map { p ->
  8. inMemoryDatastore[p.firstName] = p (2)
  9. HttpResponse.created(p) (3)
  10. }
  11. }
  12. }
1The method receives a Publisher which emits the POJO once the JSON has been read
2The map method stores the instance in a Map
3An HttpResponse is returned

Using cURL from the command line, you can POST JSON to the /people URI:

Using cURL to Post JSON

  1. $ curl -X POST localhost:8080/people -d '{"firstName":"Fred","lastName":"Flintstone","age":45}'