【发布时间】:2019-09-17 03:12:09
【问题描述】:
我有一个使用 Javax.ws.rs 实现的 GET REST API,如下所示
@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
@JacksonFeatures(serializationEnable = { SerializationFeature.INDENT_OUTPUT })
@ApiOperation(value="Returns the metadata for the specified attributes.")
@ApiResponses(value = {
@ApiResponse(code = 500, message = "Internal Server Error, Please check the logs for more details.")
})
public List<Parent> getTest(@ApiParam(value="", required=false)@RequestParam(value ="name", required = false) String name)
throws Exception {
List<Parent> children = new ArrayList<>();
children.add(new ChildA());
children.add(new ChildB());
children.add(new ChildA());
return children;
}
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = ChildA.class, name = "childA"),
@JsonSubTypes.Type(value = ChildB.class, name = "childB"),
})
interface Parent extends Serializable{
}
class ChildA implements Parent{
}
class ChildB implements Parent{
}
它工作得很好,我得到了这个 API 的以下响应:
[
{
"type": "childA"
},
{
"type": "childB"
},
{
"type": "childA"
}
]
我正在使用 Spring 4.1.2 创建相同的 API。商务舱和服务将保持不变。现在我只是为这个 API 创建一个新的 Spring 控制器:
@RequestMapping(value = "/test",method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON)
@ApiOperation(value = "data", notes="some note.")
@ApiResponses(value = {
@ApiResponse(code = 500, message = "Internal Server Error, Please check the logs for more details.")
})
public List<Parent> getTest(@ApiParam(value="", required=false)@RequestParam(value ="name", required = false) String name)
throws Exception {
List<Parent> children = new ArrayList<>();
children.add(new ChildA());
children.add(new ChildB());
children.add(new ChildA());
return children;
}
现在这个新 API 返回以下 JSON:
[
{},
{},
{}
]
我知道这是由于 Java 在编译时的类型擦除功能而发生的。 Spring 无法找出 List 的参数化类型,因此无法在序列化 JSON 中添加“类型”。 但是,这如何与旧的 Javax RS API 一起工作,以及如何在不更改返回的 JSON 格式的情况下在新 API 中解决这个问题
【问题讨论】:
标签: java json spring rest jax-rs