实用工具(一)-------java对象类、XML格式的相互转换

在上一篇文章中对于http请求的使用过程中发现,由于是系统间的交互因而请求的报文不仅仅是java对象,更多的可能是xml格式与json格式的报文,为方便后期使用,封装了一个转换工具类。
首先java对象与xml的相互转换需要使用到jaxb来实现,pom文件中加载jaxb-api。
jaxb进行转换的核心类为:Unmarshaller(xml转换为java对象)与Marshaller,首先初始化jaxbContext
JAXBContext context = JAXBContext.newInstance(classType);
然后根据转换源获取Unmarshaller或者Marshaller具体代码如下:
/**
	 * xml转换为java对象
	 * */
	@SuppressWarnings("unchecked")
	public T xmlToBean(String xml,Class classType){
		T t = null;
		try {
			JAXBContext context = JAXBContext.newInstance(classType);
			Unmarshaller unMarshaller = context.createUnmarshaller();
			t = (T)unMarshaller.unmarshal(new StringReader(xml));
			System.out.println(t);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return t;
	}
	
	/**
	 * java对象转换为xml
	 * */
	public String beanToXml(T t){
		StringBuffer buffer = new StringBuffer();
		JAXBContext context;
		Marshaller marshaller;
		try {
			context = JAXBContext.newInstance(t.getClass());
			marshaller = context.createMarshaller();
			marshaller.marshal(t, new File("test.xml"));
			InputStreamReader reader = new InputStreamReader(new FileInputStream("test.xml"));
			int temp;
			while((temp = reader.read())!=-1){
				buffer.append((char)temp);
			}
			System.out.println(buffer);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buffer.toString();
	}
通过以上方式转换时需要注意的是java对象实体必须用jaxb注解进行表述,具体如下:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {

	@XmlElement(name = "id_")
	private Integer id;
	
	@XmlElement(name = "name_")
	private String name;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	/**
	 * 
	 */
	public Student() {
		super();
	}

	@Override
	public String toString() {
		return String.format("Student [id=%s, name=%s]", id, name);
	}
	
}
其中如果需要对字段的名称进行自定义时就必须使用@XmlAccessorType(XmlAccessType.FIELD)。
若需要对xml报文进行多层嵌套,则使用集合,比如:
@XmlRootElement(name = "request")
@XmlAccessorType(XmlAccessType.FIELD)
public class Group {

	@XmlElement(name = "group_id")
	private Integer groupId;
	
	@XmlElement(name = "group_name")
	private String groupName;
	
	@XmlElementWrapper(name = "students")
	@XmlElement(name = "student")
	private List<Student> students;

	public Integer getGroupId() {
		return groupId;
	}

	public void setGroupId(Integer groupId) {
		this.groupId = groupId;
	}

	public String getGroupName() {
		return groupName;
	}

	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}

	public List<Student> getStudents() {
		return students;
	}

	public void setStudents(List<Student> students) {
		this.students = students;
	}

	@Override
	public String toString() {
		return String.format("Group [groupId=%s, groupName=%s]", groupId,
				groupName);
	}
	
	
	
	
}
,下面是测试代码:
public static void main(String[] args) {
		//xml转换为java对象
		StringBuilder sb = new StringBuilder();  
        sb.append("<?xml version='1.0' encoding='UTF-8'?>");  
        sb.append("<student>");  
        sb.append("     <id_>43283344</id_>");  
        sb.append("     <name_>中文测试</name_>");  
        sb.append("</student>");  	
		new XmlUtil().xmlToBean(sb.toString(),Student.class);
		
		
		//java对象转换为xml格式
		/*Group group = new Group();
		Student s = new Student();
		s.setId(123123);
		s.setName("测试中文");
		Student s1 = new Student();
		s1.setId(123123);
		s1.setName("测试中文");
		group.setGroupId(111);
		group.setGroupName("fredzhanghao");
		List<Student> list = new ArrayList<Student>();
		list.add(s);
		list.add(s1);
		group.setStudents(list);
		new XmlUtil().beanToXml(group);*/
	}

而对于json格式与java对象的相互转换也同理可以参考已封装的json-lib进行快速转换。

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