gpt4 book ai didi

java - 休息。 Jersey 。如何以编程方式选择返回 : JSON or XML? 的类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:40 24 4
gpt4 key购买 nike

我有两个问题:

1. 我可以创建一个类,使用 JAXB 注释(用于 XML 支持)对其进行注释并在 web.xml 中声明

<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>

是否支持 JSON(Jackson 库)?或者我需要分别为 JSON 和 XML 创建两个类?

或者可能存在一些更优雅的方法来使 REST 服务同时返回 JSON 和 XML?

2. 如何以编程方式选择要返回的类型(JSON 或 XML)?

谢谢。

最佳答案

注意:我是 EclipseLink JAXB (MOXy) JAXB (JSR-222) 的领导和成员专家组。


Can I create one class, annotate it with JAXB annotations(for XML support) and declare in web.xml for JSON (Jackson library) support?

您始终可以使用 Application 类为 JSON 绑定(bind)指定 MessageBodyReader/MessageBodyWriter。我相信 Jackson 在其 jar 中提供了一个实现。以下是将 MOXy 指定为 JSON 提供程序的 Application 类示例:

package org.example;

import java.util.*;
import javax.ws.rs.core.Application;
import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;

public class CustomerApplication extends Application {

@Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>(2);
set.add(MOXyJsonProvider.class);
set.add(CustomerService.class);
return set;
}

}

Or I need to create separately two classes for JSON and XML?

EclipseLink JAXB (MOXy) 提供 native XML 绑定(bind),旨在使您能够使用 same object model for both JSON and XML .您可以使用 MOXyJsonProvider 类将它集成到您​​的 JAX-RS 应用程序中:


How I can programmatically choose what type to return (JSON or XML)?

服务器端

您可以使用 @Produces 注释指定您的服务同时提供 XML 和 JSON 消息。

@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("{id}")
public Customer read(@PathParam("id") long id) {
return entityManager.find(Customer.class, id);
}

了解更多信息

客户端

您可以使用 MediaType 来指示消息的类型。下面是一个使用 Jersey 客户端 API 的示例。请注意 URL 是如何相同的,只是请求的媒体类型不同。

Client client = Client.create();
WebResource resource = client.resource("http://localhost:8080/CustomerService/rest/customers");

// Get XML response as a Customer
Customer customer = resource.path("1")
.accept(MediaType.APPLICATION_XML)
.get(Customer.class);
System.out.println(customer.getLastName() + ", "+ customer.getFirstName());

// Get JSON response as a Customer
Customer customer = resource.path("1")
.accept(MediaType.APPLICATION_JSON)
.get(Customer.class);
System.out.println(customer.getLastName() + ", "+ customer.getFirstName());

了解更多信息

关于java - 休息。 Jersey 。如何以编程方式选择返回 : JSON or XML? 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11382158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com