Httpservletrequest get JSON POST data
Snap up that JSON payload from an HttpServletRequest
in the blink of an eye:
In three brief lines, we snatch up the incoming JSON payload as a single string using Scanner
. No loop, no fuss. Our secret is the \\A
which is regex for the beginning of the input, so it gobbles up the entire content in a single mouthful. Later, it's over to Newton (as in Jackson) or the Gson-ovi to deserialize this puppy.
Unpacking JSON with Jackson and Gson
Once you have your JSON dressed up as a string, it's time for the deserialization promenade using either Gson or Jackson.
Jackson
Gson
And just like that, your JSON string is tossed and turned into a Java object of the type MyClass
. From here on out, it's smooth sailing! 🏄
Handling Exceptions: try
not to catch
a cold
Crunching numbers in JSON can sometimes run you into an error or two. Good for us, we've got a secret weapon up our sleeve: exception handling.
So even if your JSON throws a tantrum, your mighty app won't even flinch.
Content-Type Checkpoint
Before you go on that JSON adventure, let's make sure you've got the right map. If the HTTP request's Content-Type
header is set to application/json; charset=UTF-8
, buckle up, it's turbo time!
This check marks you safe from diving head-first into a data type disaster.
Limitations of getParameter()
: No POST
for XML
When it comes to non-JSON content types like application/x-www-form-urlencoded
, HttpServletRequest
's getParameter()
is like a fish out of water. It won't parse JSON, so we bid adieu and take the high road with getReader()
.
Encoding enigma: Special characters, meet UTF-8
In our wide wide world, special characters shouldn't feel left out. With encoding in UTF-8, nobody gets left behind.
Special characters, reporting for duty!
Was this article helpful?