创建文本/纯泽西响应

2022-01-19 00:00:00 rest web-services java jaxb jersey

我有一些有效的代码,但我正在寻找一种更好的方法来做到这一点.我有一个 RESTful Web API,我想支持 JSON、XML 和 TEXT 媒体类型.JSON 和 XML 使用 JAXB 注释的bean"很容易.班级.我刚刚让 text/plain 工作,但我希望 Jersey 更聪明一点,并且能够将我的 bean 列表 List<Machine> 转换为使用 toString 的字符串.

I have some code that works, but I am looking for a better way to do it. I have a RESTful web API that I want to support JSON, XML, and TEXT media types. The JSON and XML is easy with a JAXB annotated "bean" class. I just got text/plain to work, but I wish Jersey was a little more intelligent and would be able to convert a list of my beans, List<Machine> to a string using toString.

这里是资源类.JSON 和 XML 媒体类型使用 JAXB 注释 bean 类.纯文本使用自定义字符串格式(基本上是命令的标准输出表示).

Here is the Resource class. The JSON and XML media types use a JAXB annotated bean class. The text plain uses a custom string format (basically the stdout representation of a command).

@Path("/machines")
public class MachineResource {
    private final MachineManager manager;

    @Inject
    public MachineResource(MachineManager manager) {
        this.manager = manager;
    }

    @GET @Path("details/")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public List<Machine> details() {
        return manager.details();
    }
    @GET @Path("details/")
    @Produces({ MediaType.TEXT_PLAIN })
    public String detailsText() {
        StringBuilder text = new StringBuilder();       
        for(Machine machine : manager.details()) {
            text.append(machine.toString());
        }
        return text.toString();
    }

有没有更好的方法让 Jersey 自动转换为字符串,所以我只需要在这里实现一个方法?(可以处理所有 3 种媒体类型)

Is there a better way to do this with Jersey automatically converting to a string, so I only have to implement one method here? (That can handle all 3 media types)

我看到我可以实现一个 MessageBodyWriter,但这似乎更麻烦.

I see that I can implement a MessageBodyWriter, but that seems like a lot more trouble.

如果重要的话,我会使用嵌入式 Jetty 和 Jersey 选项.

If it matters, I am using the embedded Jetty and Jersey options.

谢谢!

推荐答案

实现 MessageBodyReader/Writer 将是您需要执行的操作,以便执行以下操作:

Implementing a MessageBodyReader/Writer would be what you need to do in order to do the following:

@GET @Path("details/")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN })
public List<Machine> details() {
    return manager.details();
}

编写的代码并不多,如果您能够编写足够通用的代码,您将能够从中获得一些重用.

It's not very much code to write, and if you are able to write it generic enough you will be able to get some re-use out of it.

相关文章