Explain Codes LogoExplain Codes Logo

Httpservletrequest get JSON POST data

java
json-deserialization
exception-handling
content-type-check
Anton ShumikhinbyAnton Shumikhin·Feb 23, 2025
TLDR

Snap up that JSON payload from an HttpServletRequest in the blink of an eye:

Scanner scanner = new Scanner(request.getInputStream(), "UTF-8"); String jsonData = scanner.useDelimiter("\\A").next(); scanner.close();

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

ObjectMapper objectMapper = new ObjectMapper(); MyClass myObject = objectMapper.readValue(jsonData, MyClass.class);

Gson

Gson gson = new Gson(); MyClass myObject = gson.fromJson(jsonData, MyClass.class);

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.

try { JSONObject jsonObject = new JSONObject(jsonData); // who knew there was an infinity gauntlet in JSON: // jsonObject.getInt(), jsonObject.getString(), etc. } catch (JSONException e) { // Houston, we have a solution, but not for the JSONException }

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!

if ("application/json; charset=UTF-8".equals(request.getContentType())) { // JSON ahoy! Dive right in! }

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.

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

Special characters, reporting for duty!