package com.hanyun.hip.mrqc.jms.uitls; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.hanyun.hip.mrqc.service.util.DateUtils; import org.jdom.Element; import org.jdom.output.XMLOutputter; import java.util.Date; public class JsonUtil { /** * 将json转化为xml * @param json * @return */ public static String JsonToXml(Object json) { if(json==null){ return null; }else{ Element elements=new Element("xml"); getXMLFromObject(json,"xml",elements); XMLOutputter xmlOut = new XMLOutputter(); String res=xmlOut.outputString(elements); return res; } } public static void getXMLFromObject(Object obj,String tag,Element parent) { if(obj==null) return; Element child; String eleStr; Object childValue; if(obj instanceof JSONObject) { JSONObject jsonObject=(JSONObject)obj; for(Object temp:jsonObject.keySet()) { eleStr=temp.toString(); childValue=jsonObject.get(temp); child=new Element(eleStr); if(childValue instanceof JSONArray) getXMLFromObject(childValue,eleStr,parent); else{ parent.addContent(child); getXMLFromObject(childValue,eleStr,child); } } }else if(obj instanceof JSONArray){ JSONArray jsonArray=(JSONArray)obj; for(int i=0;i<jsonArray.size();i++) { childValue=jsonArray.get(i); child=new Element(tag); parent.addContent(child); getXMLFromObject(childValue,tag,child); } }else if(obj instanceof Date){ parent.setText(DateUtils.dateToString((Date) obj,DateUtils.DATE_TIME_FORMAT)); }else{ parent.setText(obj.toString()); } } /** * * @param arr 需要转化为属性结构的arr * @param id 数据唯一标示 * @param pid 父id唯一标识键 * @param child 子节点键 * @return */ public static JSONArray listToTree(JSONArray arr, String id, String pid, String child){ JSONArray r=new JSONArray(); JSONObject hash=new JSONObject(); for(int i=0;i<arr.size();i++){ JSONObject json= (JSONObject) arr.get(i); hash.put(json.getString(id),json); } for(int j=0;j<arr.size();j++){ JSONObject aVal= (JSONObject) arr.get(j); JSONObject hashVP =null; if(aVal.getString(pid)!=null){ hashVP = (JSONObject)hash.get(aVal.getString(pid)); } if(hashVP!=null){ if(hashVP.get(child)!=null){ JSONArray ch= (JSONArray) hashVP.get(child); ch.add(aVal); hashVP.put(child,ch); } else{ JSONArray ch=new JSONArray(); ch.add(aVal); hashVP.put(child,ch); } }else{ r.add(aVal); } } return r; } }