杰克逊反序列化到子元素列表

时间:2019-07-30 19:35:23

标签: java jackson

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

<Trade>
  <row>
    <TradeID>1</TradeID>
  </row>
  <row>
    <TradeID>2</TradeID>
  </row>
</Trade>

我想将其反序列化为对象列表。现在我知道我可以做到

public class Trade{
  List<Row> rows;
  public class Row{
    int tradeID;
  }
}

但是理想情况下,我想避免完全基于outter标签创建类,因为它毫无价值。有什么方法可以直接将此xml反序列化为List<Row>?

1 个答案:

答案 0 :(得分:1)

如果您想直接反序列化为List<Row>,则只需在xmlMapper#readValue中指定所需的valueType即可

 String xml =
        "<Trade>\r\n"
            + "  <row>\r\n"
            + "    <TradeID>1</TradeID>\r\n"
            + "  </row>\r\n"
            + "  <row>\r\n"
            + "    <TradeID>2</TradeID>\r\n"
            + "  </row>\r\n"
            + "</Trade>\r\n"
            + "";
    XmlMapper xmlMapper = new XmlMapper();
    List<Row> rows = Arrays.asList(xmlMapper.readValue(xml, Row[].class));

    System.out.println(rows);

打印:

[Row [tradeId=1], Row [tradeId=2]]

和Row类:

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@JacksonXmlRootElement(localName = "row")
public class Row {
  @JacksonXmlProperty(localName = "TradeID")
  private int tradeId;

  public int getTradeId() {
    return tradeId;
  }

  public void setTradeId(int tradeId) {
    this.tradeId = tradeId;
  }

  @Override
  public String toString() {
    return "Row [tradeId=" + tradeId + "]";
  }
}