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
@Controller("/people")
public class PersonController {
Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>();
@Post("/saveReactive")
@SingleResult
public Publisher<HttpResponse<Person>> save(@Body Publisher<Person> person) { (1)
return Mono.from(person).map(p -> {
inMemoryDatastore.put(p.getFirstName(), p); (2)
return HttpResponse.created(p); (3)
}
);
}
}
Using Reactive Streams to Read the JSON
@Controller("/people")
class PersonController {
Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>()
@Post("/saveReactive")
@SingleResult
Publisher<HttpResponse<Person>> save(@Body Publisher<Person> person) { (1)
Mono.from(person).map({ p ->
inMemoryDatastore.put(p.getFirstName(), p) (2)
HttpResponse.created(p) (3)
})
}
}
Using Reactive Streams to Read the JSON
@Controller("/people")
class PersonController {
internal var inMemoryDatastore: MutableMap<String, Person> = ConcurrentHashMap()
@Post("/saveReactive")
@SingleResult
fun save(@Body person: Publisher<Person>): Publisher<HttpResponse<Person>> { (1)
return Mono.from(person).map { p ->
inMemoryDatastore[p.firstName] = p (2)
HttpResponse.created(p) (3)
}
}
}
1 | The method receives a Publisher which emits the POJO once the JSON has been read |
2 | The map method stores the instance in a Map |
3 | An HttpResponse is returned |
Using cURL from the command line, you can POST JSON to the /people
URI:
Using cURL to Post JSON
$ curl -X POST localhost:8080/people -d '{"firstName":"Fred","lastName":"Flintstone","age":45}'