使用Serializer从XML(List in List)读入Java类

时间:2017-12-26 09:58:16

标签: java android xml serialization xml-serialization

我确实序列化了与此示例相同而没有列表内的列表

但无法将xml序列化为列表,如果它在另一个列表中。所有类的代码和xml如下:

阅读代码:

PaymentEBillList bills = null;
try {
    Serializer serializer = new Persister();
    bills = serializer.read(PaymentEBillList.class, output);
} catch (Exception e) {     

}

执行代码

后,Bills列表为空

PaymentEBillList类:

@Root(name="ArrayOfPaymentBill")
public class PaymentEBillList {

    @ElementList(required=true, inline=true)
    public List<PaymentBill> list = new ArrayList<>();
}

PaymentBill类:

@Root(name="PaymentBill")
public class PaymentBill {
    @Element
    public String SerialNumber;
    @Element
    public String CustomerName;
    @Element
    public String TotalAmount;
    @Element
    public EBillList EBill;
    public PaymentBill()
    {
        super();
    }
    public PaymentBill(String SerialNumber, String CustomerName, String 
    TotalAmount,EBillList EBill) {
        super();
        this.SerialNumber = SerialNumber;
        this.CustomerName = CustomerName;
        this.TotalAmount = TotalAmount;
        this.EBill= EBill;
    }
}

EBillList类:

@Root(name="Bill")
public class EBillList {
    @ElementList(required=true, inline=true)
    public List<EBill> list = new ArrayList<>();
}

EBill类:

@Root(name="EBill")
public class EBill
{
    @Element
    public String NB;
    @Element
    public String Amount;
    public EBill()
    {
        super();
    }
    public EBill( String NB,String Amount) {
        super();
        this.NB = NB;
        this.Amount = Amount;
    }
}

XML:

<ArrayOfPaymentBill>
    <PaymentBill>
        <SerialNumber>1</SerialNumber>
        <CustomerName>XXX</CustomerName>
        <TotalAmount>4500.00</TotalAmount>
        <Bill>
            <EBill>
                <NB>1</NB>
                <Amount>2500.00</Amount>
            </EBill>
            <EBill>
                <NB>2</NB>
                <Amount>2000.00</Amount>
            </EBill>
        </Bill>
    </PaymentBill>
    <PaymentBill>
        <SerialNumber>2</SerialNumber>
        <CustomerName>YYY</CustomerName>
        <TotalAmount>2900.00</TotalAmount>
        <Bill>
            <EBill>
                <NB>1</NB>
                <Amount>2900.00</Amount>
            </EBill>
        </Bill>
    </PaymentBill>
</ArrayOfPaymentBill>

解决此问题的任何建议

2 个答案:

答案 0 :(得分:0)

PaymentBill.java内,您应根据XML命名EBillList

@Element
public EBillList Bill;

或在注释中指定XML名称:

@Element(name = "Bill")
public EBillList EBill;

答案 1 :(得分:0)

很抱歉,由于XML中的错误Alexey编辑问题并修正了XML,因此该问题仍然存在问题