x-stream / xstream

Serialize Java objects to XML and back again.
http://x-stream.github.io
Other
749 stars 227 forks source link

how to remove the class attribute when serializing Java Bean to xml? #333

Closed cmanlh closed 1 year ago

cmanlh commented 1 year ago

Have a class with generic type property as below:

@XStreamAlias("ipmp")
public class Ipmp<T> implements Serializable {
    private static final long serialVersionUID = -2075754377918779208L;

    private Head head;

    @XStreamAlias("body")
    private T body;

    public Head getHead() {
        return head;
    }

    public Ipmp setHead(Head head) {
        this.head = head;

        return this;
    }

    public T getBody() {
        return body;
    }

    public Ipmp setBody(T body) {
        this.body = body;

        return this;
    }
}

Do generating

XStream xStream = new XStream();
        xStream.processAnnotations(Ipmp.class);

        Ipmp ipmp = new Ipmp<BalanceInfoQuery>();

        Head head = new Head();
        head.setBusiCode("10002").setReference("req".concat(String.valueOf(System.currentTimeMillis())));
        ipmp.setHead(head);

        BalanceInfoQuery balanceInfoQuery = new BalanceInfoQuery();
        balanceInfoQuery.setAccount("01").setAccountType("02").setBankCode("03").setCurrency("USD").setDate("20230410").setQueryMode("00").setSubmitWay("00");
        ipmp.setBody(balanceInfoQuery);

        System.out.println(xStream.toXML(ipmp));

The result as below :

<ipmp>
<head>
<reference>req1681112722751</reference>
<busiCode>10002</busiCode>
</head>
<body class="xx.xx.bean.BalanceInfoQuery">
<queryMode>00</queryMode>
<bankCode>03</bankCode>
<account>01</account>
<accountType>02</accountType>
<date>20230410</date>
<currency>USD</currency>
<submitWay>00</submitWay>
</body>
</ipmp>

The body node has a attribute named class. I guess generating the class attribute for deserializing. But we don't need deserializing usring Java. The class attribute will cause issue in the next using case.

How to remove it? Does there any configuation working on it? Thanks

joehni commented 1 year ago

You can set the system attribute class to null:

xstream.aliasSystemAttribute(null, "class");

System attribute: An attribute XStream writes on its own.