Xml与Bean转换

 有些接口接收参数是Xml格式,可以通过实现这个基础类转换.减少冗余代码

/**
 * Xml Bean转换基础类
 * 
 */
public abstract class MarshallAble{
    public String marshallToString() throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(ClassUtils.getUserClass(childClass()));
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty("jaxb.encoding", "GBK");
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);

        StringWriter writer = new StringWriter();
        marshaller.marshal(this, writer);
        return writer.toString().replace(" standalone=\"yes\"", "");
    }

    public static  T unMarshallFromString(String xmlStr, Class clazz) throws JAXBException{
        JAXBContext context = JAXBContext.newInstance(ClassUtils.getUserClass(clazz));
        // 进行将Xml转成对象的核心接口
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Reader reader = new StringReader(xmlStr);
        return (T) unmarshaller.unmarshal(reader);
    }

    public abstract Class childClass();
}

 

你可能感兴趣的:(Java,Spring,java)