json转xml的步骤

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ljlsblog/article/details/79579298

写了几天的json与xml之间互相转换的工具类,现在做一下整理

用到的jar包:

    dom4j,fastjson(alibaba)

转换的思路:

        1.用stringbuffer来拼装出根标签,并将其转换为Document。

        2.获取Document的根节点,逐一添加标签和内容。

        3.添加约束时,要讲约束的地址当成第二个参数传入。例: addElement("ns2:PlaceOrder","http://siebel.com/")

        4.在添加CDATA内容时,要使用 addCDATA() 方法。


要转换的json如下:

{
	"Envelope": {
		"Body": {
			"PlaceOrder_LocalInput": {
				"PlaceOrder_LocalInput": {
					"Login": "YANXF",
					"PromotedBy": "YANXF",
					"Channel": "受理门户",
					"AccountNum": "202138621209",
					"ReviewFlag": "Y",
					"inputXML": "<?xml version=\"1.0\" encoding=\"UTF-16\"?><OrderInfo><New ServiceId=\"18918818787\" ParPromtionId=\"2-UDICJKS\" PromotionId=\"2-UDICJKS\" RootNum=\"465\" ProductStr=\"\" InstallAddress=\"柳林路158号\" BillingProfileAddress=\"柳林路158号\"/></OrderInfo>",
					"ContactPhone": "+8612341234",
					"ContactId": "1234"
				}
			}
		}
	}
}

要转换的xml格式如下:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
	<SOAP-ENV:Body>
		<m:PlaceOrder_LocalInput xmlns:m=""http://siebel.com/"">
			<PlaceOrder_LocalInput>
				<AccountNum>202112341234</AccountNum>
				<Channel>受理门户</Channel>
				<ContactAccountNum></ContactAccountNum>
				<ContactId>1234</ContactId>
				<ContactPhone>+8612341234</ContactPhone>
				<JTSDID></JTSDID>
				<Login>YANXF</Login>
				<OrderId></OrderId>
				<PromotedBy>YANXF</PromotedBy>
				<ReviewFlag>Y</ReviewFlag>
				<Warrantor_Name></Warrantor_Name>
				<inputXML>
					<![CDATA[
					<?xml version=""1.0"" encoding=""UTF-16""?>
						<OrderInfo>
							<New ServiceId="18912341234" ParPromtionId="2-UDICJKS" PromotionId="2-UDICJKS" RootNum="465" ProductStr="" InstallAddress="柳林路158号" BillingProfileAddress="柳林路158号"/>
						</OrderInfo>
					]]>
				</inputXML>
			</PlaceOrder_LocalInput>
		</m:PlaceOrder_LocalInput>
	</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

转换的java代码如下:

import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class CreateCRMLocalOrderXmlParse {
	private final static Logger LOG = LoggerFactory.getLogger(xmlParse.class);

	public static String json2Xml(JSONObject json) {
		LOG.info("---------------json转换成xml:---------------");
		
		Map<String, String> map = json2Map(json);
		Document d = null;
		try {
			if (map.get("Error_Code") == null || map.get("Error_Code").equals("")) {
				//生成头
				StringBuffer sb = new StringBuffer("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
				sb.append("</SOAP-ENV:Envelope>");
				//生成三个子标签
				d = DocumentHelper.parseText(sb.toString());
				Element root = d.getRootElement();
				Element body = root.addElement("SOAP-ENV:Body");
				Element lir= body.addElement("ns2:PlaceOrder_LocalInputResponse","http://siebel.com/");
				Element lo = lir.addElement("PlaceOrder_LocalOutput");
				
				//获取第二个PlaceOrder_LocalInput的JSONObject
				JSONObject Envelope = (JSONObject)(json.get("Envelope"));
				JSONObject Body = (JSONObject)(Envelope.get("Body"));
				JSONObject pli = (JSONObject)(Body.get("PlaceOrder_LocalInput"));
				JSONObject lopvalue = (JSONObject)(pli.get("PlaceOrder_LocalInput"));
				//把获取到的JSONObject转换成map
				Map<String, String> lopchildren = json2Map(lopvalue);
				//遍历map生成标签
				for (String key : lopchildren.keySet()) {
					if(key != "inputXML"){
						lo.addElement(key).setText(map.get(key)==null? "":map.get(key));
					}else{
						lo.addElement(key).addCDATA(map.get(key)==null? "":map.get(key));
					}
				}
			} else {
				//生成根标签
				StringBuffer sb = new StringBuffer(
						"<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">");
				sb.append("</S:Envelope>");
				//获取根标签
				d = DocumentHelper.parseText(sb.toString());
				Element root = d.getRootElement();
				//在根标签内逐级添加子标签
				Element header = root.addElement("S:Header");
				header.addElement("work:WorkContext","http://oracle.com/weblogic/soap/workarea/").setText(map.get("WorkContext"));
				Element body = root.addElement("S:Body");
				Element lir= body.addElement("ns2:PlaceOrder_LocalInputResponse","http://siebel.com/");
				Element lo = lir.addElement("PlaceOrder_LocalOutput");
				lo.addElement("Error_Code").setText(map.get("Error_Code")==null? "":map.get("Error_Code"));
				lo.addElement("Error_Message").setText(map.get("Error_Message")==null? "":map.get("Error_Message"));
				lo.addElement("ErrorCode").setText(map.get("ErrorCode")==null? "":map.get("ErrorCode"));
				lo.addElement("ErrorMessage").setText(map.get("ErrorMessage")==null? "":map.get("ErrorMessage"));
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		String strXml = d.getRootElement().asXML();
		return strXml;
	}

	public static Map<String, String> json2Map(JSONObject json) {
		Map<String, String> map = new HashMap<String, String>();
		for (Object key : json.keySet()) {
			Object value = json.get(key);
			map.put(key.toString(), value.toString());
			iteraorJson(value, map);
		}
		return map;
	}

	public static Map<String, String> iteraorJson(Object value,
			Map<String, String> map) {
		if ((value.toString().contains(":"))) {
			JSONObject json = ((JSONObject) value);
			for (Object key : json.keySet()) {
				Object value2 = json.get(key);
				map.put(key.toString(), value2.toString());
				iteraorJson(value2, map);

			}
		}
		return map;
	}
}

展开阅读全文

没有更多推荐了,返回首页