相关疑难解决方法(0)

如何自定义JAXB对象列表到JSON的序列化?

我正在使用Jersey为服务器组件创建REST Web服务.

我想在列表中序列化的JAXB注释对象如下所示:

@XmlRootElement(name = "distribution")
@XmlType(name = "tDistribution", propOrder = {
    "id", "name"
})
public class XMLDistribution {
    private String id;
    private String name;
    // no-args constructor, getters, setters, etc
}
Run Code Online (Sandbox Code Playgroud)

我有一个REST资源来检索一个看起来像这样的发行版:

@Path("/distribution/{id: [1-9][0-9]*}")
public class RESTDistribution {
    @GET
    @Produces("application/json")
    public XMLDistribution retrieve(@PathParam("id") String id) {
        return retrieveDistribution(Long.parseLong(id));
    }
    // business logic (retrieveDistribution(long))
}
Run Code Online (Sandbox Code Playgroud)

我还有一个REST资源来检索所有发行版的列表,如下所示:

@Path("/distributions")
public class RESTDistributions {
    @GET
    @Produces("application/json")
    public List<XMLDistribution> retrieveAll() {
        return retrieveDistributions();
    }
    // business logic (retrieveDistributions())
}
Run Code Online (Sandbox Code Playgroud)

我使用ContextResolver来自定义JAXB序列化,当前配置如下:

@Provider
@Produces("application/json")
public class …
Run Code Online (Sandbox Code Playgroud)

serialization json jax-rs jaxb jersey

54
推荐指数
2
解决办法
5万
查看次数

JAX-RS HATEOAS在JSON中使用Jersey,不需要的链接属性

从Jersey 2.9开始,可以通过声明性链接为超媒体驱动的REST API创建链接关系.

这段代码,例如:

@InjectLink(
    resource = ItemResource.class,
    style = Style.ABSOLUTE,
    bindings = @Binding(name = "id", value = "${instance.id}"),
    rel = "self"
)
@XmlJavaTypeAdapter(Link.JaxbAdapter.class)
@XmlElement(name="link")
Link self;
Run Code Online (Sandbox Code Playgroud)

......理论上预计会产生这样的JSON:

"link" : {
    "rel" : "self",
    "href" : "http://localhost/api/resource/1"
}
Run Code Online (Sandbox Code Playgroud)

但是,Jersey会生成不同的JSON,其中包含许多我不需要的属性:

"link" : {
   "rel" : "self",
   "uri" : "http://localhost/api/resource/1",
   "type": null,
   "uriBuilder" : null
}
Run Code Online (Sandbox Code Playgroud)

另请注意href,它使用的是代替uri.我查看了Jersey Link对象的实现并找到了JerseyLink.

我想使用Jersey的声明性链接,而不是推出我自己的实现.我最终使用Jackson注释只是为了忽略其他JerseyLink属性.

@JsonIgnoreProperties({ "uriBuilder", "params", "type", "rels" })
Run Code Online (Sandbox Code Playgroud)

有没有人使用与Jersey的声明性链接并且具有预期的JSON输出(例如,href而不是uri没有额外的Jersey属性)而不必使用JsonIgnoreProperties或其他黑客?

谢谢. …

java rest jax-rs jersey jersey-2.0

21
推荐指数
1
解决办法
1万
查看次数

标签 统计

jax-rs ×2

jersey ×2

java ×1

jaxb ×1

jersey-2.0 ×1

json ×1

rest ×1

serialization ×1