且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 JAXB 解组/编组列表<字符串>

更新时间:2022-10-20 22:21:36

我使用了@LiorH 的示例并将其扩展为:

@XmlRootElement(name="列表")公共类 JaxbList{受保护的列表列表;公共 JaxbList(){}公共JaxbList(列表列表){这个.list=列表;}@XmlElement(name="项目")公共列表 getList(){返回列表;}}代码>

请注意,它使用泛型,因此您可以将它与 String 之外的其他类一起使用.现在,应用程序代码很简单:

@得到@Path("/test2")公共 JaxbList test2(){列表列表=新向量();list.add("a");list.add("b");返回新的 JaxbList(list);}代码>

为什么 JAXB 包中不存在这个简单的类?有人在其他地方看到过类似的东西吗?

I'm trying to create a very simple REST server. I just have a test method that will return a List of Strings. Here's the code:


@GET
@Path("/test2")
public List test2(){
    List list=new Vector();
    list.add("a");
    list.add("b");
    return list;
}

It gives the following error:

SEVERE: A message body writer for Java type,
class java.util.Vector, and MIME media type,
application/octet-stream, was not found

I was hoping JAXB had a default setting for simple types like String, Integer, etc. I guess not. Here's what I imagined:


<Strings>
  <String>a</String>
  <String>b</String>
</Strings>

What's the easiest way to make this method work?

I used @LiorH's example and expanded it to:


@XmlRootElement(name="List")
public class JaxbList<T>{
    protected List<T> list;

    public JaxbList(){}

    public JaxbList(List<T> list){
        this.list=list;
    }

    @XmlElement(name="Item")
    public List<T> getList(){
        return list;
    }
}

Note, that it uses generics so you can use it with other classes than String. Now, the application code is simply:


    @GET
    @Path("/test2")
    public JaxbList test2(){
        List list=new Vector();
        list.add("a");
        list.add("b");
        return new JaxbList(list);
    }

Why doesn't this simple class exist in the JAXB package? Anyone see anything like it elsewhere?