在做项目时,自己的系统经常需要与别的系统交互,实质上是数据的交互,这就牵涉到数据格式的转换,本篇总结一下常用的几种数据格式转换,主要有实体类与json、map、xml格式的相互转换。
1、json与实体类互相转换
工具类:
package cn.usi.zhjt.pay.util;
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;
/**
* 实体类和JSON对象之间相互转化
* 依赖包jackson-all-1.7.6.jar、jsoup-1.5.2.jar
*/
public class JSONUtil {
/**
* 将json转化为实体POJO
* @param jsonStr
* @param obj
* @return
*/
public static<T> Object JSONToObj(String jsonStr,Class<T> obj) {
T t = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
t = objectMapper.readValue(jsonStr,
obj);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
/**
* 将实体POJO转化为JSON
* @param obj
* @return
* @throws JSONException
* @throws IOException
*/
public static<T> JSONObject objectToJson(T obj) throws JSONException, IOException {
ObjectMapper mapper = new ObjectMapper();
// Convert object to JSON string
String jsonStr = "";
try {
jsonStr = mapper.writeValueAsString(obj);
} catch (IOException e) {
throw e;
}
return new JSONObject(jsonStr);
}
}
demo:
json转换为实体类
//respContent,json格式参数;ResContentQyWap,json格式参数对应的实体类
ResContentQyWap resContentQy = (ResContentQyWap)JSONUtil.JSONToObj(respContent, ResContentQyWap.class);
实体类转换成json格式字符串:
//bean to json
ReqContentQy reqContentQy = new ReqContentQy();
//reqContentQy为实体类,可通过set等把信息放入实体类,JSONObject是net.sf.json.JSONObject
JSONObject object = JSONObject.fromObject(reqContentQy);
String request=object.toString();
2、实体类与map相互转换
工具类:
===================2019-06-03补充,处理类型转换异常======================
/**
* 将一个 Map 对象转化为一个 JavaBean
* @param clazz 要转化的类型
* @param map 包含属性值的 map
* @return 转化出来的 JavaBean 对象
* @throws IntrospectionException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws InvocationTargetException
*/
public static <T> T mapToBean(Class<T> clazz, Map<?, ?> map) {
T obj = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
obj = clazz.newInstance(); // 创建 JavaBean 对象
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName);
try {
if ("".equals(value) || "null".equals(value)) {
value = null;
}
Object[] args = new Object[1];
args[0] = value;
if((descriptor.getPropertyType().toString()).contains("Long") && args[0] != null){
args[0] = Long.parseLong(args[0].toString());
}
if((descriptor.getPropertyType().toString()).contains("Integer") && args[0] != null){
args[0] = Integer.parseInt(args[0].toString());
}
if((descriptor.getPropertyType().toString()).contains("Boolean") && args[0] != null){
args[0] = Boolean.valueOf(args[0].toString());
}
if((descriptor.getPropertyType().toString()).contains("Date") && args[0] != null){
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
args[0] = df.parse(args[0].toString());
}catch (Exception e){
System.out.println("日期格式转换异常e:"+e.getMessage());
try {
String date = args[0].toString().replace("Z", " UTC");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
args[0] = format.parse(date);
}catch (Exception e1){
System.out.println("日期格式转换异常e1:"+e1.getMessage());
}
}
}
descriptor.getWriteMethod().invoke(obj, args);
} catch (Exception e) {
System.out.println("字段映射失败:"+e.getMessage());
}
}
}
} catch (IllegalAccessException e) {
System.out.println("实例化 JavaBean 失败:"+e.getMessage());
} catch (IntrospectionException e) {
System.out.println("分析类属性失败:"+e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("映射错误:"+e.getMessage());
} catch (InstantiationException e) {
System.out.println("实例化 JavaBean 失败:"+e.getMessage());
}
return (T) obj;
}
=====================================================================
package com.ustcsoft.framework.util;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtilsBean;
public class MapConvertUtil {
/**
* 将JavaBean实体类转为map类型,然后返回一个map类型的值
* @param obj,要转化的JavaBean 对象
* @return 需要返回的map
*/
public static Map<String, Object> beanToMap(Object obj) {
Map<String, Object> params = new HashMap<String, Object>(0);
try {
PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
for (int i = 0; i < descriptors.length; i++) {
String name = descriptors[i].getName();
if (!"class".equals(name)) {
if(propertyUtilsBean.getNestedProperty(obj, name) != null){
params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return params;
}
/**
* 将一个 Map 对象转化为一个 JavaBean
* @param clazz 要转化的类型
* @param map 包含属性值的 map
* @return 转化出来的 JavaBean 对象
* @throws IntrospectionException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws InvocationTargetException
*/
public static <T> T mapToBean(Class<T> clazz, Map<?, ?> map) {
T obj = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
obj = clazz.newInstance(); // 创建 JavaBean 对象
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName);
if ("".equals(value)) {
value = null;
}
Object[] args = new Object[1];
args[0] = value;
try {
descriptor.getWriteMethod().invoke(obj, args);
} catch (InvocationTargetException e) {
System.out.println("字段映射失败");
}
}
}
} catch (IllegalAccessException e) {
System.out.println("实例化 JavaBean 失败");
} catch (IntrospectionException e) {
System.out.println("分析类属性失败");
} catch (IllegalArgumentException e) {
System.out.println("映射错误");
} catch (InstantiationException e) {
System.out.println("实例化 JavaBean 失败");
}
return (T) obj;
}
}
补充:某种情况,获取的map的key全是大写,例如jdbc查询的结果的字段都是大写,这时需要做点变动
/**
* 某种情况,获取的map的key全是大写,例如jdbc查询的结果的字段都是大写
* 重写mapToBean方法,bean属性与key比较时转化为大写
* @param clazz
* @param map
* @param <T>
* @return
*/
public static <T> T mapToBeanUpcase(Class<T> clazz, Map<?, ?> map) {
T obj = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
obj = clazz.newInstance(); // 创建 JavaBean 对象
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map.containsKey(propertyName.toUpperCase())) {//
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName.toUpperCase());
if ("".equals(value)) {
value = null;
}
Object[] args = new Object[1];
args[0] = value;
try {
descriptor.getWriteMethod().invoke(obj, args);
} catch (InvocationTargetException e) {
System.out.println("字段映射失败");
}
}
}
} catch (IllegalAccessException e) {
System.out.println("实例化 JavaBean 失败");
} catch (IntrospectionException e) {
System.out.println("分析类属性失败");
} catch (IllegalArgumentException e) {
System.out.println("映射错误");
} catch (InstantiationException e) {
System.out.println("实例化 JavaBean 失败");
}
return (T) obj;
}
demo:
OnlineSigningInfo onlineSign = new OnlineSigningInfo();
//onlineSign,实体类。requestMap,转化后的map格式参数
Map<String, Object> requestMap = MapConvertUtil.beanToMap(onlineSign);
//OnlineSigningInfo.class,要转化的类型 。requestMap,需要转换的map格式数据
onlineSign= MapConvertUtil.mapToBean(OnlineSigningInfo.class, requestMap);
3、实体类与xml格式数据
工具类;
package cn.usi.zhjt.pay.util;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import com.sun.org.apache.xpath.internal.XPathAPI;
public class XMLConverUtil {
/**
* 遍历list,扩展子节点
* @param sb,原有stringbuffer数据
* @param list,需要转换的list格式数据
* @throws Exception
*/
public static void getStringByList(StringBuffer sb, List list)
throws Exception {
if (list != null && list.size() != 0) {
for (Object o : list) {
sb.append("<");
//根据自己的需要给自己的list设立节点名称
sb.append("MyList");
sb.append(">");
//根据list内的数据,扩展子节点
getStringProperty(sb, o);
sb.append("</");
sb.append("MyList");
sb.append(">");
}
}
}
/**
* 将字段key与值value,拼接成"<key>value</key>"形式
* key可为String、Integer、int,此三种类型数据形成的对象和List
* @param sb
* @param vo
* @throws Exception
*/
private static void getStringProperty(StringBuffer sb, Object vo)
throws Exception {
for (Field field : vo.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object obj = field.get(vo);
if (obj != null) {
sb.append("<");
sb.append(field.getName());
sb.append(">");
//根据字段的数据格式类型处理数据
if ("java.util.List".equals(field.getType().getName())) {
//处理list类型数据,扩展子节点
getStringByList(sb, (List) obj);
} else if ("java.lang.String".equals(field.getType().getName())
|| "java.lang.Integer".equals(field.getType().getName())
|| "int".equals(field.getType().getName())) {
//String、Integer包装类和int型数据,直接设值
sb.append(obj);
} else {
getStringProperty(sb, obj);
}
sb.append("</");
sb.append(field.getName());
sb.append(">");
}
}
}
private static DocumentBuilder getDocumentBuilder()
throws ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
return dbf.newDocumentBuilder();
}
public static Document getDocument(InputSource inputSource)
throws SAXException, IOException, ParserConfigurationException {
return getDocumentBuilder().parse(inputSource);
}
/**
* 将String类型数据转换为Document类型对象
* @param text
* @return
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
*/
public static Document getDOMByString(String text) throws SAXException,
IOException, ParserConfigurationException {
InputSource in = new InputSource(new StringReader(text));
return getDocument(in);
}
public static Node string2Node(String xmlstr) throws SAXException,
IOException, ParserConfigurationException {
Document doc = string2Dom(xmlstr);
return doc.getDocumentElement();
}
public static String dom2String(Document doc) throws IOException {
doc.normalize();
StringWriter wr = new StringWriter();
OutputFormat of = new OutputFormat();
of.setOmitXMLDeclaration(true);
of.setIndenting(false);
of.setPreserveSpace(true);
XMLSerializer ser = new XMLSerializer(of);
ser.setOutputCharStream(wr);
ser.serialize(doc);
return wr.toString();
}
public static Document string2Dom(String xml) throws SAXException,
IOException, ParserConfigurationException {
return getDOMByString(xml);
}
public static NodeList getNodes(Node doc, String xpath)
throws TransformerException {
return XPathAPI.selectNodeList(doc, xpath);
}
public static Node getSingleNode(Node doc, String xpath)
throws TransformerException {
return XPathAPI.selectSingleNode(doc, xpath);
}
public static Node createElement(Document doc, String name, String value) {
Node element = doc.createElement(name);
if (value != null)
setNodeValue(element, value, true);
return element;
}
public static void setNodeValue(Node node, String value)
throws TransformerException {
if (node == null) {
return;
}
Node textNode = getSingleNode(node, "./text()");
if (textNode != null) {
textNode.setNodeValue(value);
} else {
textNode = node.getOwnerDocument().createTextNode(value);
node.appendChild(textNode);
}
}
public static void setNodeValue(Node node, String value, boolean replace) {
if (node == null) {
return;
}
Node textNode = node.getOwnerDocument().createTextNode(value);
node.appendChild(textNode);
}
/**
* Object转XML
* xml里的根元素,根据自己的需要自己设置,编码格式也是
* 子元素,从实体类里获取属性名和属性值写入
* @param vo,需要转换的实体类
* @return String,字符串
* @throws Exception
*/
public static String getStringByObject(Object vo) throws Exception {
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"gb2312\"?>");
//根据自己的需要设置根节点
sb.append("<RequestContent>");
getStringProperty(sb, vo);
sb.append("</RequestContent>");
return sb.toString();
}
/**
* XML转Object
* @param inputXML,需要转换的xml格式数据
* @param object,需要转换成的实体类型
* @return 返回需要格式的实体类对象
* @throws Exception
*/
public static <T> T getObjectByString(String inputXML,Object object) throws Exception {
//将String类型转换为Document类型对象
Document doc = getDOMByString(inputXML);
//获取第一个节点下面的所以子节点
NodeList list = doc.getFirstChild().getChildNodes();
Map<String, String> map = new HashMap<String, String>();
//遍历节点,将Document对象转换成map
for (int k = 0; k < list.getLength(); k++) {
map.put(list.item(k).getNodeName().toUpperCase(), list.item(k).getTextContent());
}
for (Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
field.set(object,map.get(field.getName().toUpperCase()));
}
return (T)object;
}
}
demo:
ReqContent4001 reqContent4001 = new ReqContent4001();
reqContent4001.setAddress("安徽合肥高新区");//通过set等设值
//bean转换为xml格式数据
String requestContentXml =XMLDomUtil.getStringByObject(reqContent4001);
//xml格式数据转换为bean
ReqContent4001 result4001 = getObjectByString(requestContentXml, ReqContent4001.class);
以上,实现了实体类与json、map、xml格式的相互转换。