Dropwizard POST请求JSON解析400错误求助
Let's walk through why you're hitting this 400 error and fix it step by step:
1. Non-Static Inner Class Breaks Deserialization
Your Entity class is a non-static inner class of UserHandler. JSON serialization frameworks (like Jackson, the default for most JAX-RS implementations) can't instantiate non-static inner classes on their own—they require an instance of the outer UserHandler class to exist first, which the framework doesn't automatically create. This is the root cause of your JSON parsing failure.
Fix: Make Entity a static inner class:
@Path("/myapp/user") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class UserHandler { @POST public Response doPost(Entity e) { System.out.println(e.id); // Return the required JSON response return Response.ok(new Entity("robert")).build(); } // Convert to static inner class public static class Entity { @JsonProperty String id; // Required: No-arg constructor for framework instantiation public Entity() {} // Optional: Parameterized constructor to easily create response objects public Entity(String id) { this.id = id; } } }
2. Missing No-Arg Constructor
Even as a static inner class, if Entity doesn't have a no-arg constructor, the framework can't reflectively create an instance of it. The code above adds this constructor, which is mandatory for JSON deserialization.
3. Mismatched Return Type (Critical for Your Desired Response)
Your original doPost method returns void, which in JAX-RS will send a 204 No Content response—this doesn't match your requirement to return { "id": "robert" }. Changing the return type to Response (or directly returning Entity) lets you send the correct JSON payload with a 200 OK status code.
4. Verify @JsonProperty Import
Double-check that you're importing the correct @JsonProperty annotation: it should be com.fasterxml.jackson.annotation.JsonProperty (from Jackson, the standard JSON library for JAX-RS). Using the wrong annotation will prevent the framework from recognizing the id field, leading to parsing failures.
The core issue here is the non-static inner class—fixing that alone will resolve the 400 error, and the other adjustments ensure your endpoint behaves exactly as you expect.
内容的提问来源于stack exchange,提问作者Moondaws1

