2

我在使用 JAX-rs 将 ArrayList 从服务器发送到客户端时遇到问题。我有4节课:

演示 - 正在启动 REST 服务器 FileDetails - 有 3 个字段存储数据 ConfigFiles - 它几乎没有文件方法,并且有一个 FileDetails 对象列表 RestServer - 有方法 GET

我有以下代码:

@XmlRootElement(name="FileDetails")
@Path("/easy")
public class RestSerwer {

    @GET
    @Path("/temporary")
    @Produces("text/temporary")
    public String methodGet() { 
        ConfigFiles cf = ConfigFiles.getInstance();
           List<FileDetails> files = cf.getList();
                   try {
                       JAXBContext ctx = JAXBContext.newInstance(ArrayList.class, FileDetails.class);
                       Marshaller m = ctx.createMarshaller();
                       StringWriter sw = new StringWriter();
                       m.marshal(files, sw);
                       return sw.toString();
                   } catch (JAXBException e) {
                       e.printStackTrace();
                   }
                   return null;
    }
}

在客户端,我有 GetRest:

public class GetRest{

    HttpClient client = null;
    GetMethod method = null;
    private String url = null;

    public GetRest(String url) {
        this.url = url;
    }

    public String getBody(String urlDetail){
           client = new HttpClient();
           method = new GetMethod(url + urlDetail);
           method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
           new DefaultHttpMethodRetryHandler(3, false));
           try {
                client.executeMethod(method);
            } catch (HttpException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            byte[] responseBody = null;
            try {
                responseBody = method.getResponseBody();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{                   
                method.releaseConnection();
            }
            String str = new String(responseBody);
            return str;
    }   

    public String getFiles(){   
        return getBody("/easy/temporary");
    }   
}

当我尝试:

GetRest getRestClass = new GetRest("http://localhost:8185");
                        //List<FileDetails> cf = new ArrayList<FileDetails>();
                        String xxxx = getRestClass.getFiles(); // TODO

它抛出:

Caused by: com.sun.istack.internal.SAXException2: unable to marshal type "java.util.ArrayList" as an element because it is missing an @XmlRootElement annotation

在服务器端。

任何人都可以帮助我吗?

谢谢

4

1 回答 1

1

您基本上有 2 种可能性:创建您自己的类,它是列表顶部的包装器,或者编写您自己的提供程序并将其注入球衣中,以便它知道如何编组/解组数组列表。这是第一个解决方案的简单代码:

@XmlRootElement
public class MyListWrapper {

    @XmlElement(name = "List")
    private List<String> list;

    public MyListWrapper() {/*JAXB requires it */

    }

    public MyListWrapper(List<String> stringList) {
        list = stringList;
    }

    public List<String> getStringList() {
        return list;
    }

}
于 2012-05-09T14:51:23.930 回答