简体   繁体   中英

Jackson deserialize to list of child elements

I have an xml that looks like this

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

And I'd like to deserialize this into a list of objects. Now I know I could do

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

But ideally I'd like to avoid creating a class based on the outter tag entirely because it's worthless. Is there any way I could deserialize this xml directly to a List<Row>?

If you'd like to deserialize into List<Row> directly , you can just specify the desired valueType in xmlMapper#readValue

 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);

prints:

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

And Row class:

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 + "]";
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM