我有一个使用 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 Controller :
@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 中添加“type”。 但是,这如何与旧的 Javax RS API 配合使用,以及如何在新 API 中修复此问题而不更改返回的 JSON 格式
最佳答案
这实际上是 Jackson 的一个功能,不依赖于 JAX-RS 或 Spring Boot。
在 Spring Boot 应用程序中,您可以使用与以前相同的 @JsonTypeInfo 和 @JsonSubTypes 注释来注释父接口(interface)和子类,并且类型推断将像以前一样工作。 Jackson 应该已经包含在您的 Spring Boot 应用程序的依赖项/类路径中(通过父 POM)。
关于java - Spring 和 Javax RS REST API 中继承时序列化 JSON 的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55887357/