The topic of this post is pretty lightweight. A bit of a lark, really, but Spring Java coders may find it interesting and maybe even useful. We’re looking at the most efficient way of serving a single JSON Key-Value Pair in Spring MVC. Our ideal result would look like this:
{
"key" : "some value"
}
On the client we would use it like this.
$.getJSON('/json/posts/map', null, function (data) {
$("#keyvalue").html(data["key"]);
});
Okay, back to our Spring MVC Controller. First let’s look at the Class annotations, @RestController and @JsonRequestMapping. Spring’s @RestController frees us from having to annotate our methods with @ResponseBody. @JsonRequestMapping is an Interface we added to economize our class methods even further, freeing us from adding mapping properties like
produces = MediaType.APPLICATION_JSON_VALUE.
With @RestController and the ability to assign mapping properties at the class level, our methods are nice and clean as you’ll see in a bit.
Here’s the JsonRequestMapping class. It’s based on this #stackoverflow post from Ali Dehghani.
So that’s cool.
Back to the Controller and our main objective of producing a simple JSON Key-Value pair in Spring MVC. Time to paste in the entire PostRestController class. Each method is commented with the JSON it produces, which demonstrates…variations on a JSON Key-Value Pair Theme.
Source Code Notes for this Post
All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.