JAXB解组XML以使用通用对象

时间:2019-06-01 08:55:12

标签: java

我可以用通用封送模型,但是使用模型创建的xml,我不能将其解组。

我的模特:

@XmlRootElement(name = "user")    
@XmlAccessorType(XmlAccessType.FIELD)    
@Data    
public class User<T> {
    private String id;
    @XmlElement
    private String name;
    @XmlAnyElement
    private T t;

}

@Data    
@XmlAccessorType(XmlAccessType.FIELD)    
@XmlRootElement(name = "address")    
public class Address {

    @XmlElement
    private String city;

}

而JaxbUtil是:

    public static String convertToXml(Object obj, String encoding) throws Exception {
        String result;
        JAXBContext context = JAXBContext.newInstance(obj.getClass(), Address.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        result = writer.toString();

        return result;
    }

    public static <T> T convertToJavaBean(String xml, Class<T> clazz) throws Exception {
        T t;
        JAXBContext context = JAXBContext.newInstance(clazz, Address.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        t = (T) unmarshaller.unmarshal(new StringReader(xml));
        return t;
    }

我可以封送用户

        User<Address> user = new User<>();
        Address address = new Address();
        address.setCity("3");
        user.setId("1");
        user.setName("2");
        user.setT(address);
        try {
            String str = TestClass.convertToXml(user, "UTF-8");
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        }

xml是

    <user>
        <id>1</id>
        <name>2</name>
        <address>
            <city>3</city>
        </address>
    </user>

但是使用这个xml,我无法解组模型

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                "<user>\n" +
                "    <id>1</id>\n" +
                "    <name>2</name>\n" +
                "    <address>\n" +
                "        <city>3</city>\n" +
                "    </address>\n" +
                "</user>";


        try {
            User<Address> user = new User<>();
            Address address = new Address();
            user.setT(address);
            user = TestClass.convertToJavaBean(xml, user.getClass());
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

结果是

User(id=1, name=2, t=[address: null])

类地址为空,那么如何用通用解组模型

0 个答案:

没有答案