xmlbeanjson互转工具,可直接CV就用

Posted hsz-csy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了xmlbeanjson互转工具,可直接CV就用相关的知识,希望对你有一定的参考价值。

1、jar包

<dependency>
     <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6.1</version>
</dependency>
<dependency>
       <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
         <classifier>jdk15</classifier>
</dependency>
 <dependency>
        <groupId>xom</groupId>
        <artifactId>xom</artifactId>
        <version>1.2.5</version>
</dependency>
<dependency>
        <groupId>com.alibaba</groupId>
         <artifactId>fastjson</artifactId>
         <version>1.2.31</version>
</dependency>

2、工具类

package com.jbf.util;

import com.alibaba.fastjson.JSONObject;
import net.sf.json.xml.XMLSerializer;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/*********************************
 * 类描述:
 * @author huangsz
 * @date 2019/11/20
 * @version v1.0
 **********************************/
public class XmlUtil {

    public static Object xmlToBean(Element rootElt, Class pojo) throws Exception {
        // 首先得到pojo所定义的字段
        Field[] fields = pojo.getDeclaredFields();
        // 根据传入的Class动态生成pojo对象
        Object obj = pojo.newInstance();
        for (Field field : fields) {
            // 设置字段可访问(必须,否则报错)
            field.setAccessible(true);
            // 得到字段的属性名
            String name = field.getName();
            // 这一段的作用是如果字段在Element中不存在会抛出异常,如果出异常,则跳过。
            try {
                rootElt.elementTextTrim(name);
            }
            catch (Exception ex) {
                continue;
            }
            if (rootElt.elementTextTrim(name) != null && !"".equals(rootElt.elementTextTrim(name))) {
                // 根据字段的类型将值转化为相应的类型,并设置到生成的对象中。
                if (field.getType().equals(Long.class) || field.getType().equals(long.class)){
                    field.set(obj, Long.parseLong(rootElt.elementTextTrim(name)));
                } else if (field.getType().equals(String.class)) {
                    field.set(obj, rootElt.elementTextTrim(name));
                } else if (field.getType().equals(Double.class) || field.getType().equals(double.class))
                {
                    field.set(obj, Double.parseDouble(rootElt.elementTextTrim(name)));
                } else if (field.getType().equals(Integer.class) || field.getType().equals(int.class))
                {
                    field.set(obj, Integer.parseInt(rootElt.elementTextTrim(name)));
                } else if (field.getType().equals(java.util.Date.class))
                {
                    field.set(obj, Date.parse(rootElt.elementTextTrim(name)));
                } else {
                    continue;
                }
            }
        }
        return obj;
    }

    public static <T> T xmlToBean(String xml,Class<T> clazz) {
        T t = null;
        try {
            List<T> ts = xmlToList(xml, clazz);
            if (!ts.isEmpty()) {
                t = ts.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据解析错误");

        }
        return t;
    }

    /**
     * DMO4J写入XML
     * @param obj        泛型对象
     * @param entityPropertys 泛型对象的List集合
     */
    public static <T> String beanToXml(T obj, List<T> entityPropertys) {
        //效率检测
        long lasting = System.currentTimeMillis();
        String xmlStr = null;
        try {
            Document document = DocumentHelper.createDocument();
            // 获得类名
            String rootname = obj.getClass().getSimpleName();
            // 添加根节点
            Element root = document.addElement(rootname+"s");
            // 获得实体类的所有属性
            Field[] properties = obj.getClass().getDeclaredFields();
            // 递归实体
            for (T t : entityPropertys) {
                // 二级节点
                Element secondRoot = root.addElement(rootname);
                for (int i = 0; i < properties.length; i++) {
                    // 反射get方法
                    Method meth = t.getClass().getMethod(
                            "get"
                                    + properties[i].getName().substring(0, 1)
                                    .toUpperCase()
                                    + properties[i].getName().substring(1));
                    // 为二级节点添加属性,属性值为对应属性的值
                    secondRoot.addElement(properties[i].getName()).setText(
                            meth.invoke(t).toString());

                }
            }
            xmlStr = document.asXML();
            System.out.println("document字符串"+xmlStr);
            long lasting2 = System.currentTimeMillis();
            System.out.println("写入XMLtoString结束,用时"+(lasting2 - lasting)+"ms");
        } catch (Exception e) {
            System.out.println("XML文件写入失败");
            e.printStackTrace();
        }
        return xmlStr;
    }

    /**
     *
     * @param XMLPathAndName XML文件的路径和地址
     * @param t     泛型对象
     * @return
     */
    public static <T> List<T> xmlToList(String XMLPathAndName, Class<T> t) {
        long lasting = System.currentTimeMillis();
        List<T> list = new ArrayList<>();
        try {
            Document doc = DocumentHelper.parseText(XMLPathAndName);
            // 获得根节点
            Element root = doc.getRootElement();
            // 二级节点
            Element foo;
            Iterator i = root.elementIterator();
            while (i.hasNext()) {
                // 下一个二级节点
                foo = (Element) i.next();
                T t2 = (T)xmlToBean(foo, t);
                list.add(t2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        long lasting2 = System.currentTimeMillis();
        System.out.println("读取XMLtoString结束,用时"+(lasting2 - lasting)+"ms");
        return list;
    }

    public static JSONObject xml2Json(String xml){
        XMLSerializer xmlSerializer = new XMLSerializer();
        String read = xmlSerializer.read(xml).toString();
        return JSONObject.parseObject(read);
    }

    public static String json2Xml(net.sf.json.JSONObject json, String rootName) throws DocumentException {
        String sXml = "";
        XMLSerializer xmlSerializer = new XMLSerializer();
        xmlSerializer.setTypeHintsEnabled(false);
        xmlSerializer.setRootName(rootName);
        String sContent = xmlSerializer.write(json,"utf-8");
        try {
            Document docCon = DocumentHelper.parseText(sContent);
            sXml = docCon.getRootElement().asXML();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return sXml;
    }

}

3、测试验证

 javaBean类:

public class TestBean {

    private int id;
    private String dealTime;
    private String status;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDealTime() {
        return dealTime;
    }

    public void setDealTime(String dealTime) {
        this.dealTime = dealTime;
    }

    public String getStatus() {
        return status;
    }

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

    @Override
    public String toString() {
        return "TestBean{" +
                "id=" + id +
                ", dealTime=‘" + dealTime + ‘‘‘ +
                ", status=‘" + status + ‘‘‘ +
                ‘}‘;
    }
}

 

package com.jbf.util;

import com.alibaba.fastjson.JSONObject;

import java.util.List;

/*********************************
 * 类描述:
 * @author huangsz
 * @date 2019/11/20
 * @version v1.0
 **********************************/
public class App {
    public static void readXml() {
        try {
            String xml = "<?xml version="1.0" encoding="UTF-8"?>
" +
                    "<TestBeans>" +
                    "<TestBean><id>1</id><dealTime>20070510165424</dealTime><status>2</status></TestBean>" +
//                    "<TestBean><id>2</id><dealTime>20070510165424</dealTime><status>2</status></TestBean>" +
//                    "<TestBean><id>3</id><dealTime>20070510165424</dealTime><status>2</status></TestBean>" +
//                    "<TestBean><id>4</id><dealTime>20070510165424</dealTime><status>2</status></TestBean>" +
//                    "<TestBean><id>5</id><dealTime>20070510165424</dealTime><status>2</status></TestBean>" +
                    "</TestBeans>";
            List<TestBean> list = XmlUtil.xmlToList(xml, TestBean.class);
            System.out.println("list = " + list.size());
            for (TestBean bean : list) {
                System.out.println(bean);
            }
            TestBean bean = XmlUtil.xmlToBean(xml, TestBean.class);
            System.out.println(bean);
            JSONObject jsonObject = XmlUtil.xml2Json(xml);
            System.out.println(jsonObject);
            //
            String str = "{"TestBean":{"dealTime":"20070510165424","id":"1","status":"2"}}";
            net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(str);
            String testBeans = XmlUtil.json2Xml(fromObject, "TestBeans");
            System.out.println(testBeans);
            TestBean bean1 = XmlUtil.xmlToBean(testBeans, TestBean.class);
            System.out.println(bean1);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        readXml();
    }

}

 

以上是关于xmlbeanjson互转工具,可直接CV就用的主要内容,如果未能解决你的问题,请参考以下文章

Java工程编码格式由GBK转化成utf-8(编码格式互转)

Java工程编码格式由GBK转化成utf-8(编码格式互转)

磁力链接与BT种子互转工具怎么用?使用方法

海康威视摄像头对接SDK实时预览功能和抓拍功能,懒癌福利,可直接CV

java long和java.lang.Long有啥区别?

shp与json互转(转载)