Jackson解析XML

使用Jackson

maven项目的pom.xml依赖

        <dependency>
	  <groupId>com.fasterxml.jackson.dataformat</groupId>
	  <artifactId>jackson-dataformat-xml</artifactId>
	  <version>2.9.0</version>
	</dependency>
	<dependency>
	  <groupId>com.fasterxml.woodstox</groupId>
	  <artifactId>woodstox-core</artifactId>
	  <version>5.1.0</version>
	</dependency>    

  

User.java

public class User {
	private int id;
	private String username;
	private String sex;
	private String birthday;
	private String address;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
				+ address + "]";
	}
	public User() {
	}
	public User(int id, String username, String sex, String birthday, String address) {
		super();
		this.id = id;
		this.username = username;
		this.sex = sex;
		this.birthday = birthday;
		this.address = address;
	}
}

  

Jackson.java

 POJO转为XML

public static void jacksonBean2XML() throws JsonProcessingException{
//		JacksonXmlModule module = new JacksonXmlModule();
//		module.setDefaultUseWrapper(false);
		
		XmlMapper xmlMapper = new XmlMapper();
		xmlMapper.setDefaultUseWrapper(false);
		User user=new User(1,"lucas","nan","2019-10-01","上海");
		String xml=xmlMapper.writeValueAsString(user);
		System.out.println(xml);
	}

  

返回

<User><id>1</id><username>lucas</username><sex>nan</sex><birthday>2019-10-01</birthday><address>上海</address></User>

  

XML转为POJO

public static void jacksonXML2Bean() throws JsonParseException, JsonMappingException, IOException{
//		JacksonXmlModule module = new JacksonXmlModule();
//		module.setDefaultUseWrapper(false);
		XmlMapper xmlMapper = new XmlMapper();
		xmlMapper.setDefaultUseWrapper(false);
		//自动忽略无法对应pojo的字段
		xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		User user=xmlMapper.readValue("<User><id>1</id><username>lucas</username><sex>nan</sex><birthday>2019-10-01</birthday><address>上海</address></User>", User.class);
		System.out.println(user);
	}

  

返回

User [id=1, username=lucas, sex=nan, birthday=2019-10-01, address=上海]

  

 

posted on 2019-04-22 16:47  乌云上  阅读(5753)  评论(3编辑  收藏  举报

导航