为了解决 Jersey 中无法正确序列化具有(仅)一个元素的列表的错误,即:
"list":"thing"
代替
"list": [ "thing" ]
我已经编写了下面的代码,它几乎可以解决它,但是(真气)让我无法告诉它不要将整个结果用双引号括起来,如下所示:
"list": "[ "thing" ]"
我别无选择,我会非常感谢任何看透这一点的人。请注意,我还尝试将ContextResolver < JAXBContext >作为一些帖子建议的@Provider解决方案,但 Jersey 根本不会调用该代码。此解决方案是唯一接近的解决方案。
顺便说一下,这是 POJO 中的消费字段:
@XmlAnyElement
@XmlJavaTypeAdapter( JaxBListAdapter.class )
private List< String > list = new ArrayList< String >();
这是代码:
public class JaxBListAdapter extends XmlAdapter< Element, List< String > >
{
private static Logger log = Logger.getLogger( JaxBListAdapter.class );
private DocumentBuilder documentBuilder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
@Override
public Element marshal( List< String > list )
{
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement( "list" );
document.appendChild( rootElement );
if( list != null )
{
StringBuilder sb = new StringBuilder();
sb.append( "[ " );
boolean first = true;
for( String item : list )
{
if( first )
first = false;
else
sb.append( ", " );
sb.append( "\"" + item + "\"" );
}
sb.append( " ]" );
rootElement.setTextContent( sb.toString() );
}
return rootElement;
}
@Override
public List< String > unmarshal( Element rootElement )
{
// Hmmmm... never callled?
NodeList nodeList = rootElement.getChildNodes();
List< String > list = new ArrayList< String >( nodeList.getLength() );
for( int x = 0; x < nodeList.getLength(); x++ )
{
Node node = nodeList.item( x );
if( node.getNodeType() == Node.ELEMENT_NODE )
list.add( node.getTextContent() );
}
return list;
}
}