json转xml的步骤

写了几天的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;
	}
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Hutool是一个Java开发工具包,提供了丰富实用的工具方法,包括JSONXML换功能。 要使用Hutool进行JSONXML,首先需要添加Hutool的依赖到项目中。然后可以使用JSONUtil类的方法来进行换。 以下是一个使用Hutool进行JSONXML的示例代码: ```java import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import cn.hutool.json.XML; public class JsonToXmlExample { public static void main(String[] args) { // 定义一个JSON对象 JSONObject json = JSONUtil.createObj(); json.put("name", "John"); json.put("age", 28); json.put("email", "john@example.com"); // 将JSON对象XML字符串 String xmlStr = JSONUtil.toXmlStr(json); System.out.println(xmlStr); // 将XML字符串JSON对象 JSONObject jsonObj = XML.toJSONObject(xmlStr); System.out.println(jsonObj); // 可以继续对JSON对象进行操作 System.out.println(jsonObj.getStr("name")); System.out.println(jsonObj.getInt("age")); System.out.println(jsonObj.getStr("email")); // 可以将JSON对象XML字符串,再JSON对象,循环操作 String xmlStr2 = JSONUtil.toXmlStr(jsonObj); JSONObject jsonObj2 = XML.toJSONObject(xmlStr2); System.out.println(jsonObj2); } } ``` 在上述代码中,我们首先创建了一个JSONObject对象,然后使用JSONUtil类的toXmlStr方法将其换为XML格式的字符串。接着使用XML类的toJSONObject方法将XML字符串再换回JSON对象。最后,我们可以对JSON对象进行操作,例如获取其属性值。 这就是使用Hutool进行JSONXML的基本步骤和示例代码。使用Hutool的JSONXML换功能可以方便地在Java开发中进行数据格式换。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值