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 Reactor. The following is an example of a controller that reads and saves an incoming POJO in a non-blocking way from JSON:
Using RxJava 2 to Read the JSON
@Controller("/people")
public class PersonController {
Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>();
@Post("/saveReactive")
public Single<HttpResponse<Person>> save(@Body Single<Person> person) { (1)
return person.map(p -> {
inMemoryDatastore.put(p.getFirstName(), p); (2)
return HttpResponse.created(p); (3)
}
);
}
}
Using RxJava 2 to Read the JSON
@Controller("/people")
class PersonController {
ConcurrentHashMap<String, Person> inMemoryDatastore = [:]
@Post("/saveReactive")
Single<HttpResponse<Person>> save(@Body Single<Person> person) { (1)
person.map({ p ->
inMemoryDatastore.put(p.getFirstName(), p) (2)
HttpResponse.created(p) (3)
})
}
}
Using RxJava 2 to Read the JSON
@Controller("/people")
class PersonController {
internal var inMemoryDatastore: MutableMap<String, Person> = ConcurrentHashMap()
@Post("/saveReactive")
fun save(@Body person: Single<Person>): Single<HttpResponse<Person>> { (1)
return person.map { p ->
inMemoryDatastore[p.firstName] = p (2)
HttpResponse.created(p) (3)
}
}
}
1 | The method receives a RxJava Single which emits the POJO once the JSON has been read |
2 | The map method is used to store the instance in Map |
3 | An HttpResponse is returned |
Using CURL from the command line you can POST JSON to the /people
URI for the server to receive it:
Using CURL to Post JSON
$ curl -X POST localhost:8080/people -d '{"firstName":"Fred","lastName":"Flintstone","age":45}'