Json XML互相转换工具类

pom

<dependency>
			<groupId>com.alibabagroupId>
			<artifactId>fastjsonartifactId>
			<version>1.2.62version>
dependency>

java

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import com.alibaba.fastjson.JSONArray;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.linlinjava.litemall.core.config.BaseTrade;
import org.linlinjava.litemall.core.config.TransResult;
import org.xml.sax.SAXException;

import com.alibaba.fastjson.JSONObject;

/**
 * @author :XXX
 * @description :Json XML 转换
 * @date : 2019/10/31 9:35
 */
public class JsonXmlUtils  extends BaseTrade {
     
    private static final String ENCODING = "UTF-8";

    /**
     * JSON对象转xml字符串
     *
     * @param json JSON对象
     * @return xml字符串
     */
    public static TransResult<String> jsonToPrettyXml(JSONObject json , String character)  {
     
        TransResult<String> transResult = new TransResult();
        if (json == null || StringUtil.isEmpty(character)){
     
            transResult.failure("参数异常");
        }
        try {
     
            Document document = jsonToDocument(json,character);
            /* 格式化xml */
            OutputFormat format = OutputFormat.createPrettyPrint();
            // 设置缩进为4个空格
            format.setIndent(" ");
            format.setIndentSize(4);
            format.setEncoding(character);
            StringWriter formatXml = new StringWriter();
            XMLWriter writer = new XMLWriter(formatXml, format);
            writer.write(document);
            transResult.success();
            transResult.setObject(formatXml.toString());
        } catch (SAXException e) {
     
            logger.error(e.getMessage(), e);
            transResult.failure("XML解析异常:"+e.getMessage());
        }catch (IOException e){
     
            logger.error(e.getMessage(), e);
            transResult.failure("XML格式化异常:"+e.getMessage());
        }

        return transResult;
    }


    /**
     * XML字符串转JSON对象
     *
     * @param xml xml字符串
     * @return JSON对象
     * @throws DocumentException
     */
    public static TransResult<JSONObject> xmlToJson(String xml)  {
     
        TransResult<JSONObject> transResult = new TransResult();
        if (StringUtil.isEmpty(xml)){
     
            transResult.failure("参数异常");
        }
        try {
     
            JSONObject json = new JSONObject();
            SAXReader reader = new SAXReader();
            Document document  = reader.read(new StringReader(xml));
            Element root = document.getRootElement();
            json.put(root.getName(), elementToJson(root));
            transResult.success();
            transResult.setObject(json);
        } catch (DocumentException e) {
     
            logger.error(e.getMessage(), e);
            transResult.failure("XML解析异常:"+e.getMessage());
        }
        return transResult;
    }


    /**
     * JSON对象转Document对象
     *
     * @param json JSON对象
     * @return Document对象
     * @throws SAXException
     */
    private static Document jsonToDocument(JSONObject json,  String character) throws SAXException {
     
        Document document = DocumentHelper.createDocument();
        document.setXMLEncoding(character);

        // root对象只能有一个
        for (String rootKey : json.keySet()) {
     
            Object obj =  json.get(rootKey);
            Element root = null;
            if (obj instanceof JSONObject) {
     
                root = jsonToElement( (JSONObject)obj , rootKey);
                document.add(root);
            }else if (obj instanceof JSONArray) {
     
                JSONArray jo = (JSONArray)obj;
                for (int i = 0; i< jo.size();i++ ) {
     
                    root = jsonToElement( (JSONObject)jo.get(i) , rootKey);
                    document.add(root);
                }

            }
            break;
        }
        return document;
    }

    /**
     * JSON对象转Element对象
     *
     * @param json JSON对象
     * @param nodeName 节点名称
     * @return Element对象
     */
    private static Element jsonToElement(JSONObject json, String nodeName) {
     
        Element node = DocumentHelper.createElement(nodeName);
        for (String key : json.keySet()) {
     
            try {
     
                Object child = json.get(key);
                if (child instanceof JSONObject) {
     
                    node.add(jsonToElement(json.getJSONObject(key), key));
                } else if (child instanceof JSONArray) {
     
                    JSONArray jo = (JSONArray) child;
                    for (int i = 0; i < jo.size(); i++) {
     
                        Object co =  jo.get(i);
                        if(co instanceof JSONObject){
     
                            node.add(jsonToElement((JSONObject)co, key));
                        }else{
     
                            Element element = DocumentHelper.createElement(key);
                            element.setText(co.toString());
                            node.add(element);
                        }
                    }
                } else {
     
                    Element element = DocumentHelper.createElement(key);
                    element.setText(json.getString(key));
                    node.add(element);
                }
            }catch (Exception e){
     
                e.printStackTrace();
            }
        }

        return node;
    }

    /**
     * Element对象转JSON对象
     *
     * @param element Element对象
     * @return JSON对象
     */
    private static JSONObject elementToJson(Element element) {
     
        JSONObject json = new JSONObject();
        for (Object child : element.elements()) {
     
            Element e = (Element) child;
            if (e.elements().isEmpty()) {
     
                json.put(e.getName(), e.getText());
            }

            else {
     
                json.put(e.getName(), elementToJson(e));
            }
        }

        return json;
    }

}

你可能感兴趣的:(Java工具类)