xml字符串与JavaBean的相互转化

最近对接数据,返回的数据格式是酱紫的:


    
        
        
        
    

当时真心想泪奔,这玩意怎么做成类啊,偶不会啊~~

然而为了工资,拼了!

我用的是javax带的注解,感觉挺好用的,简单方便,不知道为啥一开始居然没看明白~~

首先从网上查了一下,写了个工具类:


import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * 
 * Class Name: XmlConvertUtil  
 * Description: xml格式转化工具类
 *
 */
public class XmlConvertUtil {
	/**
     * xml转换成JavaBean
     *
     * @param xml xml格式字符串
     * @param t 待转化的对象
     * @return 转化后的对象
     * @throws Exception JAXBException
     */
    @SuppressWarnings({ "unchecked" })
	public static  T convertToJavaBean(String xml, Class t) throws Exception {
        T obj = null;
        JAXBContext context = JAXBContext.newInstance(t);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        obj = (T) unmarshaller.unmarshal(new StringReader(xml));
        return obj;
    }
    
    /** 
     * JavaBean转换成xml 
     * @param obj 
     * @param encoding  
     * @return  
     */  
    public static String convertToXml(Object obj, String encoding) {  
        String result = null;  
        try {  
            JAXBContext context = JAXBContext.newInstance(obj.getClass());  
            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();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        return result;  
    }  
    
}

然后是对应的实体类,这里我发现有个比较心塞的地方,这里的xml套了三层,我也必须写三个实体类来对应~~~

1、层:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "oa")    //这个类的根节点
public class RequestEntity {
  
	@XmlElement  //标签注解,如果是属性需要用@XmlAttribute
    protected RequestBody informations; //这里对应节点
    
	public RequestBody getInformations() {
		return informations;
	}
	
	public void setInformations(RequestBody informations) {
		this.informations = informations;
	}
    
    
}

2、层:


import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "informations")
public class  RequestBody{
	@XmlElement(name="information") //名字和标签名相同name可以不写
	public List information; //对应列表

	public List getInformation() {
		return information;
	}

	public void setInformation(List information) {
		this.information = information;
	}

}

3、层,也就是要得到的实体:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import com.ly.cloud.news.po.NewsData;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "information")
public class NewsDataXMLVO {

        @XmlAttribute
        private String id;
        @XmlAttribute
        private String title;
        @XmlAttribute
        private String time;
        
        public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getTitle() {
			return title;
		}
		public void setTitle(String title) {
			this.title = title;
		}
		
}

然后就可以调用了:

public static void main(String[] args) throws ClientProtocolException, IOException {
		try {
			///////////////////////将xml转换成JavaBean开始///////////////////////////
			RequestEntity entity = convertToJavaBean(getNewsByTagId("ff80808105cda730010"),RequestEntity.class);
			RequestBody body = entity.getInformations();
			List xmlVo = body.getInformation();
			for (NewsDataXMLVO newsDataXMLVO : xmlVo) {
				System.out.println(newsDataXMLVO.getId() + " " + newsDataXMLVO.getTitle());
			}
			////////////////////////将xml转化成JavaBean结束///////////////////////////
			
			///////////////////////将JavaBean转化成xml开始////////////////////////////
			RequestBody body2 = new RequestBody();
			body2.setInformation(xmlVo);
			RequestEntity entity2 = new RequestEntity();
			entity2.setInformations(body2);
			String xml = convertToXml(entity2, "utf-8");
			System.out.println("xml:" + xml);
			///////////////////////将JavaBean转化成xml结束///////////////////////////
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

ps:getNewsByTagId("ff80808105cda730010")是我和远程对接的方法,返回的是xml格式的String字符串。

你可能感兴趣的:(springboot)