1

JSON是:

{"list": [1,2,3,4,5,6,7,8,9,10]}

以下是我实现 JAXB bean 的方法:

package com.anon.sortweb.jaxb;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;

@XmlRootElement
public class JsonBean {
    @XmlElement(name="list")
    private int[] list;

    public JsonBean() {}

    public void setList(int[] list) {
        this.list = list;
    }

    public int[] getList() {
        return list;
    }
}

我的 Web 应用程序运行良好(我能够成功访问其他资源),但是这个资源(我将 JSON 传递给)返回了 415 Media Type Unsupported 异常。

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces("text/html")
public String sortAndReturnHtml(JsonBean listBean) { ... }

如何正确编写我的 JAXB bean 来封装整数列表?

提前致谢!

4

1 回答 1

1

注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB (JSR-222)专家组的成员。

您的 JAXB bean 是您的 JSON 数据的完全合理的表示。JAXB (JSR-222)规范不涵盖 JSON 绑定,因此答案最终归结为您的 JAX-RS 实现如何/是否解释 JAXB 元数据以生成/使用 JSON。

演示

下面是它如何与 MOXy 一起工作。

package forum13648734;

import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {JsonBean.class}, properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource json = new StreamSource("src/forum13648734/input.json");
        JsonBean jsonBean = unmarshaller.unmarshal(json, JsonBean.class).getValue();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(jsonBean, System.out);
    }

}

输入.json/输出

{"list":[1,2,3,4,5,6,7,8,9,10]}

了解更多信息

于 2012-11-30T20:48:38.037 回答