Jersey:没有找到适合类型 [simple type, class Thing] 的构造函数:无法从 JSON 对象实例化

2022-01-21 00:00:00 java jackson jersey jersey-2.0

我有一个资源,其方法如下:

@PUT@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)@Path("/添加")公共响应 putThing(Thing thing) {尝试 {//对Thing对象做一些事情返回 Response.status(HttpStatus.SC_OK).build();} 捕捉(异常 e){log.error("请求失败", e);返回 Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build();}}

事情:

公共类事物{私有最终字符串符号;私有最终字符串名称;公共股票(字符串符号,字符串名称){this.symbol = 符号;this.name = 名称;}公共字符串 getSymbol() {返回 this.symbol;}公共字符串 getName() {返回这个名称;}}

当我发出 PUT 请求时:

PUT/rest/add HTTP/1.1主机:本地主机:8135内容类型:应用程序/json缓存控制:无缓存{"symbol":"some symbol","name":"some name"}

我收到以下回复:

<块引用>

没有为类型 [简单类型,类 Thing] 找到合适的构造函数:可以不从 JSON 对象实例化(缺少默认构造函数或创建者,或者可能需要添加/启用类型信息?)

为什么 Jersey/Jackson 没有将我的 JSON 对象反序列化到我的 POJO 中?

解决方案

你需要一个无参数的构造函数和setter,或者使用@JsonCreator.最简单的事情就是在 setter 中添加无参数.Jackson 在反序列化时需要设置器.对于序列化,只需要 getter.

编辑

为了保持不可变,您可以在构造函数上使用 @JsonCreator.例如

@JsonCreatorpublic Thing(@JsonProperty("symbol") 字符串符号,@JsonProperty("name") 字符串名称) {this.symbol = 符号;this.name = 名称;}

查看更多杰克逊注解:@JsonCreator 揭秘p>

I have a resource with a method like:

@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/add")
public Response putThing(Thing thing) {
    try {
        //Do something with Thing object
        return Response.status(HttpStatus.SC_OK).build();
    } catch (Exception e) {
        log.error("Request failed", e);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build();
    }
}

Thing:

public class Thing {
    private final String symbol;
    private final String name;

    public Stock(String symbol, String name) {
        this.symbol = symbol;
        this.name = name;
    }

    public String getSymbol() {
        return this.symbol;
    }

    public String getName() {
        return this.name;
    }
}

When I make a PUT request like:

PUT /rest/add HTTP/1.1
Host: localhost:8135
Content-Type: application/json
Cache-Control: no-cache

{"symbol":"some symbol","name":"some name"}

I get the following response:

No suitable constructor found for type [simple type, class Thing]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)

Why is Jersey/Jackson not deserializing my JSON object into my POJO?

解决方案

You need a no-arg constructor and setters, or use @JsonCreator. Easiest thing to do would be just to add the no-arg with setters. Jackson needs the setters when deserializing. For serialization, all that's needed are getters.

EDIT

To keep it immutable, you can use @JsonCreator on the constructor. For example

@JsonCreator
public Thing(@JsonProperty("symbol") String symbol, 
             @JsonProperty("name") String name) {

    this.symbol = symbol;
    this.name = name;
}

See more Jackson Annotations: @JsonCreator demystified

相关文章