【发布时间】:2019-04-25 12:56:00
【问题描述】:
我正在尝试为 Liferay 创建一个 REST API 模块,但在尝试从我的网络服务生成 JSON 响应时遇到了问题。
我想生成一个像这样的简单 JSON:
{
"status": "ok",
"message": "News not found for ID: 5"
}
但是,这就是我得到的:
{
"parentResponse": {
"status": "ok",
"message": "News not found for ID: 5"
}
}
这是我的 POJO 类:
@XmlRootElement
public class ParentResponse {
public String status, message;
public Object item;
public ParentResponse() {
}
public ParentResponse(String status, String message, Object item) {
this.status = status;
this.message = message;
this.item = item;
}
}
返回 json 的我的网络服务:
// return a single news based on supplied ID
@GET
@Path("{id}")
@Produces("application/json")
public Response getNewsById(@PathParam("id") String id) {
ResponseBuilder builder;
try {
News news = findById(new Long(id));
if (news != null) {
builder = Response.ok(news);
}
else { // This is my POJO class returned as a JSON
ParentResponse parentResponse = new ParentResponse("ok", "News not found for ID: " + id, null);
builder = Response.status(Response.Status.NOT_FOUND).entity(parentResponse);
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.build();
}
那么,如何获取没有根标签的 JSON?我尝试在 @XmlRootElement 注释旁边添加 (name=""),但这不起作用。
【问题讨论】:
-
你不尝试使用 jackson 来编组你的 bean 吗?
-
如何将它添加到我的项目的 build.gradle 文件中?我试图添加这个:compileInclude group: 'com.fasterxml.jackson.core', name: 'jackson-core' 但这不起作用。
-
尝试在模块的 build.gradle 中添加以下行:
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.9.0" compile "com.fasterxml.jackson.core:jackson-annotations:2.9.0" -
感谢@javaxiss 这似乎有效。但是现在,我该怎么办?
-
您应该在模型属性 (ParentResponse) 上使用
@JsonProperty,如下所示:@JsonInclude(JsonInclude.Include.NON_EMPTY) public class ParentResponse { @JsonProperty("message") public String message; @JsonProperty("status") public String status; ... }