1. 程式人生 > >JSON(不帶json陣列)轉XML(層層巢狀,xml格式為value格式)

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>