创建文本/纯泽西响应 [英] Create a text/plain Jersey response

查看:18
本文介绍了创建文本/纯泽西响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些有效的代码,但我正在寻找一种更好的方法来做到这一点.我有一个 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.

这篇关于创建文本/纯泽西响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆