使用 xstream 将 XMLl 转换为 Java 对象

Convert XMLl to Java object using xstream

我有以下 xml。如何使用 xstream 转换为 java 对象。我尝试了几种方法,但最终得到了 conversionexception。 代码如下。我不知道如何转换为 BookDetails 对象。

XML 字符串:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Books>
    <bookdetails>
    <bookId>20</bookId>
    <bookName>AAAA</bookName>
    <amount>35</amount>
    </bookdetails>
    </Books>

图书详情class:

@XStreamAlias("bookDetails")
public class BookDetails {
@XStreamAlias("bookId")
private int bookId;
@XStreamAlias("bookName")
private String bookName;
@XStreamAlias("amount")
private int amount;
//getters and setters
}

书籍class:

@XStreamAlias("Books")
public class Books{

@XStreamAlias("bookDetails")
private List<BookDetails> bookDetails=new ArrayList<BookDetails>();
}

--------------unmarshall class method----

public BookDetails convertXml(String xml){

            xstream.processAnnotations(Books.class);
            xstream.processAnnotations(BookDetails.class);
            xstream.addImplicitCollection(Books.class,"BookDetails");
            return (BookDetails)xstream.fromXML(processOrderXML);
}

您的代码有几个问题。

首先,您为 BookDetails class 使用了错误的别名。您将其声明为 @XStreamAlias("bookDetails"),而您的 XML 标签全部为小写 bookdetails

那么您使用了错误的字段名称来定义隐式集合:它应该是 bookDetails - 作为您的列表字段名称,而不是 BookDetails.

最后,您必须解析完整的 XML,然后您可以从中获取 BookDetails 数据。而不是创建 BookDetails 个实例 XStream 会给你 Books 个实例。

作为补充观察,您不必为名称与 XML 标签完全相同的字段添加别名。

更正后的代码为:

@XStreamAlias("bookdetails")
public class BookDetails
{
    private int bookId;
    private String bookName;
    private int amount;
}

@XStreamAlias("Books")
public class Books
{
    private List<BookDetails> bookDetails = new ArrayList<BookDetails>();
}

public BookDetails convertXml(String xml)
{
    xstream.processAnnotations(Books.class);
    xstream.processAnnotations(BookDetails.class);
    xstream.addImplicitCollection(Books.class, "bookDetails");
    Books b = (Books) xstream.fromXML(xml);
    // and now you can return your BookDetails element (in case you want only first one)
    return b.bookDetails.get(0);
}