如何在REST Web服务中使用json生成http响应?

时间:2011-05-25 06:59:12

标签: java web-services rest mongodb jersey

我想在网络服务中使用json进行响应,如下所示:

HTTP/1.1 200 OK
Content-Type: application/vnd.org.snia.cdmi.dataobject+json
X-CDMI-Specification-Version: 1.0
{
"objectURI" : "/MyContainer/MyDataObject.txt",
"objectID" : "AABwbQAQb/ENV52Ai8a3MA==",
"parentURI" : "/MyContainer/",
"mimetype" : "text/plain",
"metadata" : {
"cdmi_size" : "17"
},
"valuerange" : "0-17",
"value" : "Hello CDMI World!"
}

但现在我只能表现出像

HTTP/1.1 200 OK
Content-Type: application/vnd.org.snia.cdmi.dataobject+json
X-CDMI-Specification-Version: 1.0
{
"objectURI" : "/MyContainer/MyDataObject.txt",
"objectID" : "AABwbQAQb/ENV52Ai8a3MA==",
"parentURI" : "/MyContainer/",
}   

如何在"meta" : {....}之后放置"mimetype"。如何将"meta"作为 BasicDBObject 或其他类型?我使用jersey框架编写Web服务和java。

感谢

1 个答案:

答案 0 :(得分:1)

在Jersey将它们序列化为JSON之前,您需要使用JAXB Binding注释来注释对象。下面是一个示例类,请注意您可以使用@XmlType批注的propOrder属性对元素重新排序。也可以提供除方法名称以外的XML元素名称。

@XmlRootElement
@XmlType(propOrder = { "name", "elements" })
public class ExampleObject implements Serializable {

    private static final long serialVersionUID = 1L;
    private Collection<String> elements = null;
    private String name = null;

    @XmlElementWrapper(name = "elements")
    @XmlElement(name = "element")
    public Collection<String> getElements() {
        return this.elements;
    }

    public String getName() {
        return this.name;
    }

    public void setElements(final Collection<String> elements) {
            this.elements = elements;
    }

    public void setName(final String name) {
            this.name = name;
    }

}