Edd*_*Edd 27 java jersey jackson jersey-2.0
我有一个资源,其方法如下:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
事情:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我发出PUT请求时:
PUT /rest/add HTTP/1.1
Host: localhost:8135
Content-Type: application/json
Cache-Control: no-cache
{"symbol":"some symbol","name":"some name"}
Run Code Online (Sandbox Code Playgroud)
我收到以下回复:
找不到类型[simple type,class Thing]的合适构造函数:无法从JSON对象实例化(缺少默认构造函数或创建者,或者可能需要添加/启用类型信息?)
为什么Jersey/Jackson没有将我的JSON对象反序列化为我的POJO?
Pau*_*tha 40
你需要一个no-arg构造函数和setter,或者使用@JsonCreator.最简单的事情就是添加无定型的setter.在反序列化时杰克逊需要安装者.对于序列化,所需的只是getter.
编辑
为了使其不可变,您可以@JsonCreator在构造函数上使用它.例如
@JsonCreator
public Thing(@JsonProperty("symbol") String symbol,
@JsonProperty("name") String name) {
this.symbol = symbol;
this.name = name;
}
Run Code Online (Sandbox Code Playgroud)
查看更多Jackson Annotations:@JsonCreator揭秘
| 归档时间: |
|
| 查看次数: |
44001 次 |
| 最近记录: |