JSON(不带json数组)转XML(层层嵌套,xml格式为value格式)

废话不多说,直接上代码

/**
 * 处理json数据
 * @param jsonString
 */
public static String jsonToXmlUtil(String jsonString){
    if(!StringUtils.hasText(jsonString)){
        log.error("{}","请求参数不能为空");
        throw new BizException("EEEEEE","请求参数不能为空");
    }
    JSONObject jsonObj=null;
    try{
        //格式化JSON数据,将json字符串转化为JSONObject并将数据的key以字母顺序排序
        jsonObj=JSON.parseObject(jsonString);
        }catch(Exception e){
        log.error("{}","请求参数格式有误");
        throw new BizException("EEEEEE","请求参数格式有误");
    }
    String xmlResult=null;
    Document document=DocumentHelper.createDocument();
    document.setXMLEncoding("UTF-8");
    Element rootEle=document.addElement("Message");
    Element element=rootEle.addElement("Public");
    jsonObjToXml(jsonObj,element);
    xmlResult=document.asXML();
    return xmlResult;
}

public static void jsonObjToXml(JSONObject jsonObject,Element element){
    for(String key:jsonObject.keySet()){
        if(jsonObject.get(key)instanceof JSON){
            Element child=element.addElement(key);
            jsonObjToXml((JSONObject)jsonObject.get(key),child);
        }else{
            Element child=element.addElement(key);
            child.addAttribute("value",jsonObject.get(key).toString());
        }
    }
}

测试:

public static void main(String[] args) throws Exception {
    String json = "{\"TxnBatchNo\":\"20170607152322\",\"TxnSeq\":\"1\",\"CardNo\":\"2017000100000003\",\"AAA\":{\"hello\":\"nihao\",\"hey\" : \"hai\",\"world\": \"hee\"},\"BBB\":{\"hello\":\"nihao\",\"hey\" : \"hai\",\"people\": {\"d\" : \"dog\",\"c\" : \"\",\"e\" : {\"hello\":\"nihao\",\"hey\" : \"hai\",\"tiger\": {\"d\" : \"dog\",\"c\" : \"\",\"e\" : \"elepahant\"}}}}}";
    System.out.println(jsonToXmlUtil(json));
}

输出结果:

<?xml version="1.0" encoding="UTF-8"?>
<Message><Public><BBB><hello value="nihao"/><hey value="hai"/><people><d value="dog"/><e><hello value="nihao"/><hey value="hai"/><tiger><d value="dog"/><e value="elepahant"/><c value=""/></tiger></e><c value=""/></people></BBB><AAA><hello value="nihao"/><hey value="hai"/><world value="hee"/></AAA><TxnSeq value="1"/><TxnBatchNo value="20170607152322"/><CardNo value="2017000100000003"/></Public></Message>

猜你喜欢

转载自blog.csdn.net/sinat_30035833/article/details/81221680