最代码官方的gravatar头像
最代码官方2015-01-22 11:51:42

java通过JAXB框架转换xml为java bean对象代码片段分享

java可以通过配置xml文件来转换为bean,代码片段如下:

JaxbUtil.java

package com.zuidaima.script.util;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JaxbUtil {

	/**
	 * JavaBean转换成xml
	 * 默认编码UTF-8
	 * @param obj
	 * @param writer
	 * @return 
	 */
	public static String convertToXml(Object obj) {
		return convertToXml(obj, "UTF-8");
	}

	/**
	 * 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转换成JavaBean
	 * @param xml
	 * @param c
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T converyToJavaBean(String xml, Class<T> c) {
		T t = null;
		try {
			JAXBContext context = JAXBContext.newInstance(c);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			t = (T) unmarshaller.unmarshal(new StringReader(xml));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return t;
	}
}

projects.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<projectList>
	<projects>	
		<project>
			<id>1</id>
			<name><![CDATA[新闻发布1]]></name>
			<type>3</type>
			<userId>2</userId>
			<content><![CDATA[新闻1<img src="http://a.hiphotos.baidu.com/news/crop%3D31%2C0%2C598%2C359%3Bw%3D638/sign=094971085f6034a83dade2c1f6207878/3b87e950352ac65c80549e7af8f2b21193138a62.jpg">]]></content>
			<extendJson></extendJson>
			<channelId>21</channelId>
			<sourceId>3</sourceId>
		</project>
		
		<project>
			<id>2</id>
			<name><![CDATA[机构职能1]]></name>
			<type>1</type>
			<userId>2</userId>
			<content><![CDATA[机构职能1http://www.zuidaima.com]]></content>
			<extendJson></extendJson>
			<channelId>12</channelId>
			<sourceId>3</sourceId>
		</project>
			
	</projects>
</projectList>

Projects.java

package com.zuidaima.script.util;

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.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

import com.zuidaima.module.Project;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "projectList")
public class Projects {
	@XmlElementWrapper(name = "projects")
	@XmlElement(name = "project")
	private List<Project> projects;

	public List<Project> getProjects() {
		return projects;
	}

	public void setProjects(List<Project> projects) {
		this.projects = projects;
	}

}

Project.java

package com.zuidaima.module;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;

import net.sf.json.JSONObject;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.jackson.annotate.JsonIgnore;

import com.zuidaima.constants.ModuleConstants;
import com.zuidaima.util.StringUtil;

@Entity
@Table(name = "cms_project")
public class Project extends BaseEntity {
	private String name = "";
	private int type;
	private long userId;
	private User user;
	private String content = "";
	private String htmlContent = "";
	private int status = ModuleConstants.MODULE_STATUS_NORMAL;
	private JSONObject extend;
	private String extendJson = "";
	private long channelId;
	private long sourceId;
	private BaseEntity source;
	private long targetId;

	public Project() {
		this.createTime = new Date();
		this.updateTime = createTime;
	}

	@Column(name = "name")
	public String getName() {
		return this.name;
	}

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

	@Column(name = "type")
	public int getType() {
		return this.type;
	}

	public void setType(int type) {
		this.type = type;
	}

	@Column(name = "user_id")
	public long getUserId() {
		return this.userId;
	}

	public void setUserId(long userId) {
		this.userId = userId;
	}

	@Transient
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Column(name = "content")
	public String getContent() {
		return this.content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	@Transient
	public String getHtmlContent() {
		if (content != null) {
			htmlContent = StringUtil.formatContent(content);
		}
		return htmlContent;
	}

	public void setHtmlContent(String htmlContent) {
		this.htmlContent = htmlContent;
	}

	@Column(name = "status")
	@JsonIgnore
	public int getStatus() {
		return this.status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	@JsonIgnore
	@Column(name = "extend_json")
	public String getExtendJson() {
		return this.extendJson;
	}

	public void setExtendJson(String extendJson) {
		this.extendJson = extendJson;
	}

	@Transient
	public JSONObject getExtend() {
		if (extendJson == null || extendJson.trim().equals("")) {
			extend = new JSONObject();
		} else {
			try {
				extend = JSONObject.fromObject(extendJson);
			} catch (Exception e) {
				extend = new JSONObject();
			}
		}
		return extend;
	}

	public void setExtend(JSONObject extend) {
		this.extend = extend;
	}

	@JsonIgnore
	@Column(name = "channel_id")
	public long getChannelId() {
		return this.channelId;
	}

	public void setChannelId(long channelId) {
		this.channelId = channelId;
	}

	@JsonIgnore
	@Column(name = "source_id")
	public long getSourceId() {
		return this.sourceId;
	}

	public void setSourceId(long sourceId) {
		this.sourceId = sourceId;
	}

	@JsonIgnore
	@Transient
	public BaseEntity getSource() {
		return source;
	}

	public void setSource(BaseEntity source) {
		this.source = source;
	}

	@JsonIgnore
	@Column(name = "target_id")
	public long getTargetId() {
		return this.targetId;
	}

	public void setTargetId(long targetId) {
		this.targetId = targetId;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}

调用:

String path = JaxbTest.class.getResource("").getFile();
File file = new File(path + "projects.xml");

String str = FileUtils.readFileToString(file, "utf-8");

Projects projects = JaxbUtil.converyToJavaBean(str, Projects.class);
for (Project project : projects.getProjects()) {
	project.setUpdateTime(project.getCreateTime());
	projectService.save(project);
}

打赏

顶部客服微信二维码底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友