How do return Java List<String> Json using Jax-RS

守給你的承諾、 提交于 2019-12-01 06:53:46

With JAXB there are two type's of List supported. The first is a List of elements, the second a delimited string (a "normal" XML value or attribute, which is parsed into a list using some delimiter). The first seems to be what you want ("array").

For reference, see: http://jaxb.java.net/jaxb20-ed/api/javax/xml/bind/annotation/XmlList.html

You will note that in both cases the List you want would need to be encapsulated by some other object. Fundamentally, XML (and by extension JAXB) likes to trace everything back to a single root node/object. So to model it, you need something like this:

@XmlRootElement(name="wrapper")
public abstract class ListWrapper {
   public List<String> names;
}

Then your methods would need to be changed to accept/return ListWrapper objects and extract the actual List from it.

I tried the same without success, so I ended with packing a string into one field object.

return listWithString
                .stream()
                .map(
                        stringElement -> {
                            MyBoxObject bo = new MyBoxObject();
                            bo.setSomeField(stringElement);
                            return bo;
                        })
                .collect(Collectors.toList());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!