2

我有一个看起来像这样的 xml 文档:

<response>
  <total>1000</total>
  <warning>warning1</warning>
  <warning>warning2</warning>
</response>

我的对象如下所示:

public class Response {
    private BigDecimal total;

    private List<String> warnings=new ArrayList<String>();

    public List<String> getWarnings() {
        return warnings;
    }

    public void setWarnings(List<String> warnings) {
        this.warnings = warnings;
    }

    public BigDecimal getTotal() {
        return total;
    }

    public void setTotal(BigDecimal total) {
        this.total = total;
    }

    public void addWarning(String warning) {
        warnings.add(warning);
    }
}

我正在尝试像这样映射它:

Digester digester = new Digester();
digester.setValidating( false );
digester.addObjectCreate( "response", Response.class );
digester.addBeanPropertySetter( "response/total", "total" );
digester.addObjectCreate("response/warning","warnings", ArrayList.class);
digester.addCallMethod("response/warning", "add", 1);
digester.addCallParam("response/warning", 0);
ret = (Rate)digester.parse(new ByteArrayInputStream(xml.getBytes()));

但是,我无法让它填充列表。总数确实设置正确。对于它的价值,我无法控制 XML,但可以更改我的 Response 对象。有任何想法吗?提前致谢。

4

1 回答 1

4

您的类中已经有addWarning方法Response并且warnings也已初始化。只需重写您的规则:

    Digester digester = new Digester();
    digester.setValidating( false );
    digester.addObjectCreate("response", Response.class );
    digester.addBeanPropertySetter("response/total", "total" );
    digester.addCallMethod("response/warning", "addWarning", 1);
    digester.addCallParam("response/warning", 0);

就这样。

于 2011-11-16T04:23:33.403 回答