如何使restful Response中的自定義對象看起來像本機類型。換句話說,我不想使用getter和setter,而是讓對象編組並且像字符串一樣解組。我可以使用unmarshall的構造函數,但我不知道如何通過服務的響應來獲取對象。當我運行樣本時,我得到了這個結果:如何在響應中創建一個RESTful服務處理自定義對象?
<data>
<nType>123</nType>
<myType/>
<notMyType>
<value>def</value>
</notMyType>
</data>
我想讓myType看起來像nType。下面是一個簡短的代碼示例:
package rscust;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.xml.bind.annotation.XmlRootElement;
@Path("/")
public class Service extends Application {
@XmlRootElement
public static class Data {
public String nType;
public MyType myType;
public NotMyType notMyType;
public Data() {}
}
// custom class does not work in Response
public static class MyType {
private String value;
public MyType() {}
public MyType(String value) {
this.value=value;
}
public String toString() {
return value;
}
}
// works with getter and setter, but I don't want that
public static class NotMyType {
private String value;
public NotMyType() {}
public NotMyType(String value) {
this.setValue(value);
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@GET
@Produces(value={MediaType.APPLICATION_XML})
public Response get(
@QueryParam(value = "ntype")String nType,
@QueryParam(value = "mytype")MyType myType,
@QueryParam(value = "notmytype")NotMyType notMyType
) {
Data data = new Data();
data.nType = nType;
data.myType = myType;
data.notMyType = notMyType;
return Response.ok().entity(data).build();
}
private HashSet<Object> singletons;
public Service() {
super();
singletons = new HashSet<Object>();
singletons.add(this);
}
public Set<Object> getSingletons() {
return singletons;
}
}
結帳以下帖子http://stackoverflow.com/questions/17533280/resteasy-jax-rs-sending-custom-object-in-response-body – sasankad
你使用的是什麼庫或框架? – SpacePrez
我正在嘗試使用RESTEasy。這是否意味着我需要一個MessageBodyWriter? – NicholasKarl