在XstreamAliasing中使用冒号的异常

时间:2017-02-21 18:11:53

标签: java xml-parsing xstream

我从服务器获取一个字符串作为响应。我想使用XStream将该字符串转换为java pojos。我的一些领域的名字中有冒号,例如@XStreamAlias(S:Envelope)

在解析期间,它显示错误“CannotResolveClassException:Envelope”。但是,如果我使用

@XStreamAlias(Envelope)

工作正常。 如何告诉Xstream在字段名称中允许冒号(“:”)?

1 个答案:

答案 0 :(得分:0)

它为我工作:

import java.io.InputStream;

import org.junit.Test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

import lombok.Data;


public class ColonAlias {

    @Test
    public void smokeTest() {
        InputStream file = ColonAlias.class.getResourceAsStream(ColonAlias.class.getSimpleName()+ ".xml");
        XStream xStream = new XStream();
        xStream.ignoreUnknownElements();
        xStream.processAnnotations(Parent.class);

        Parent parent = (Parent) xStream.fromXML(file);

        System.out.println(parent);
    }

    @XStreamAlias("parent")
    @Data
    public class Parent {

        @XStreamAsAttribute
        private String name;

        @XStreamAlias("p:age")
        private String age;
    }
}

XML:

<?xml version="1.0" encoding="UTF-8"?>
<parent name="Adam">
        <p:age>33</p:age>
</parent>

输出:

ColonAlias.Parent(name=Adam, age=33)