jackson使用xml转json

前端之家收集整理的这篇文章主要介绍了jackson使用xml转json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package com.testtt.main.uu;


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 + "]"; } }

原文链接:https://www.f2er.com/xml/294379.html

猜你在找的XML相关文章