如何在REST Web服务中传递自定义对象 [英] How to pass a custom object in REST webservice
问题描述
我在将自定义对象传输到客户端时遇到问题.如何将自定义对象传输到客户端并将其接收回Web服务?我正在按块传输文件.我想知道我应该怎么写我的客户.我尝试在客户端中将其作为MediaType.APPLICATION_JSON
传递,但是没有任何结果,这意味着它不会传递回Web服务.下面是一些正在处理的代码.
i'm having problems transfering a custom object to the client. How can i transfer a custom object to the client and receive it back to the webservice? i'm transferring a file by chunks. i want to know how i should write my client. i tried passing it as MediaType.APPLICATION_JSON
in client but i get no result meaning it doesn't get passed back to the webservice. Below is a bit of code im working on.
网络服务
@POST
@Path("/fileTransfer")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public final TransferInfomation transferInfo(final FileModel file)
{
...
}
...(一些代码)(只说一个 syso )
...(some code)(lets just say a syso)
FileModel类
public class FileModel {
private String fileID;
private DataHandler dataHandler;
/**
* Constructor.
*/
public FileModel() {
}
(让我们假设创建了setter和getters)
(lets assume setters and getters are made)
(不确定Web服务是否正确).还在学习REST,我想知道客户端应该如何.
(Not sure if the webservice is correct). Still learning REST, i want to know how the client should be.
提前谢谢.
推荐答案
在Jersey中封送"和解组"自定义对象"(JSON,XML等)的一种好方法是使用JAXB( https://jaxb.java.net/).
A good way to "marshal" and "unmarshal" "custom objects" (in JSON, XML, etc.) in Jersey is to use JAXB (https://jaxb.java.net/).
要执行此操作,您需要创建一个"jaxb类",并带有适当的getter和setter(和注释),例如:
To do this you need to create a "jaxb class", with the proper getters and setters (and annotations), e.g.:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class FileModel{
private String fileID;
private DataHandler dataHandler;
public String getFileID(){
return fileID;
}
public void setFileID(String fileID){
this.fileID = fileID;
}
public DataHandler getDataHandler(){
return dataHandler;
}
public void setDataHandler(DataHandler dataHandler){
this.dataHandler = dataHandler;
}
}
不要忘记声明@XmlRootElement
.然后,您可以简单地在API端点(方法)中声明和使用这些对象:
Do not forget to declare the @XmlRootElement
. Then you can simply declare and use these objects in your API endpoints (methods):
@POST
@Path("/fileTransfer")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public final FileModel transferInfo(FileModel file)
{
// read file in "FileModel" format
// ... make several operations
// return new FileModel (or another format if you will)
}
这应该有效.确保在客户端正确遵循为FileModel定义的数据结构.此处查看有关如何在泽西岛处理该问题的示例:
This should work. Make sure you follow the data structure defined for FileModel correctly in the client side. See here a example on how to handle that in Jersey: How do I POST a Pojo with Jersey Client without manually convert to JSON? (where JAXB is also used).
这篇关于如何在REST Web服务中传递自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!