创建文本/纯泽西响应

编程入门 行业动态 更新时间:2024-10-11 21:28:10
本文介绍了创建文本/纯泽西响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

创建文本/纯泽西响应

本文发布于:2023-10-12 04:35:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483728.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   泽西

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!