import java.io.StringWriter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.testtt.main.model.User;
public class XmlUtil {
private static XmlMapper xmlMapper = new XmlMapper();
private static ObjectMapper objectMapper = new ObjectMapper();
/**
* xml字符串转成JSON格式字符串
*
* @param xmlStr
* @return
*/
public static String convertXmlToJson(String xml) {
StringWriter w = new StringWriter();
try {
JsonParser jp = xmlMapper.getFactory().createParser(xml);
JsonGenerator jg = objectMapper.getFactory().createGenerator(w);
while (jp.nextToken() != null) {
jg.copyCurrentEvent(jp);
}
jp.close();
jg.close();
} catch (Exception e) {
e.printStackTrace();
}
return w.toString();
}
/**
* JSON转换成Object
*
* @param jsonStr
* JSON格式字符串
* @param valueType
* 对象
* @return
*/
public static <T> T readValue(String jsonStr,Class<T> clazz) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.readValue(jsonStr,clazz);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<user>"
+ "<address>jianXi</address><age>2</age><name>xiaoMing</name><sex>yy</sex><userId>22</userId>"
+ "</user>";
String json = convertXmlToJson(xml);
System.out.println(json);
System.out.println(
readValue(convertXmlToJson(xml),User.class).toString());
}
}
/******User******/
package com.testtt.main.model; import javax.xml.bind.annotation.XmlRootElement; //@XmlRootElement public class User { private String name; private String sex; private String address; private int age; private int userId; public User() { } public User(String name,String sex,String address,int age,int userId) { this.name = name; this.sex = sex; this.address = address; this.age = age; this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } @Override public String toString() { return "User [name=" + name + ",sex=" + sex + ",address=" + address + ",age=" + age + ",userId=" + userId + "]"; } }