xml字符串与JavaBean的相互转化

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

<oa>
    <informations>
        <information id="gdfggdfgd" time="2018-07-01" title="AAA"></information>
        <information id="tetyeyh" time="2018-07-18" title="BB"></information>
        <information id="kuiyuytj" time="2018-07-20" title="CC"></information>
    </informations>
</oa>

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

然而为了工资,拼了!

我用的是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> T convertToJavaBean(String xml, Class<T> 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、<oa>层:

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; //这里对应<informations>节点
    
	public RequestBody getInformations() {
		return informations;
	}
	
	public void setInformations(RequestBody informations) {
		this.informations = informations;
	}
    
    
}

2、<informations>层:


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<NewsDataXMLVO> information; //对应<information>列表

	public List<NewsDataXMLVO> getInformation() {
		return information;
	}

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

}

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

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<NewsDataXMLVO> 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字符串。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值