You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dropwizard POST请求JSON解析400错误求助

Fixing the 400 "Unable to process JSON" Error in Your JAX-RS User Handler

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:47:47