精华内容
下载资源
问答
  • JAVA JSON转XML

    2020-12-02 09:25:25
    主要jar包用到dom4j和...public class JsonToXml { private static final String STR_JSON = "{\"name\":\"yato233\",\"address\":{\"city\":\"beijing\",\"street\":\" longyu Road \",\"postcode\":100000},\"bl.

    主要jar包用到dom4j和gson。大致思路就是写一个方法遍历json的每一个key和value,碰到有深度的key重复调用本方法(也就是递归啦)

     

    public class JsonToXml {
    	private static final String STR_JSON = "{\"name\":\"yato233\",\"address\":{\"city\":\"beijing\",\"street\":\" longyu Road \",\"postcode\":100000},\"blog\":\"https://blog.csdn.net/baidu_38322198\"}";
    
    	/**
    	 * 将json字符串转换成xml
    	 * 
    	 * @param json
    	 *            json字符串
    	 * @param parentElement
    	 *            xml根节点
    	 * @throws Exception
    	 */
    	public static Element jsonToXml(String json, Element parentElement) throws Exception {
    		JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
    		Element ee = toXml(jsonObject, parentElement, null);
    		return ee;
    	}
    
    	/**
    	 * 将json字符串转换成xml
    	 * 
    	 * @param jsonElement
    	 *            待解析json对象元素
    	 * @param parentElement
    	 *            上一层xml的dom对象
    	 * @param name
    	 *            父节点
    	 */
    	public static Element toXml(JsonElement jsonElement, Element parentElement, String name) {
    		if (jsonElement instanceof JsonArray) {
    			//是json数据,需继续解析
    			JsonArray sonJsonArray = (JsonArray)jsonElement;
    			for (int i = 0; i < sonJsonArray.size(); i++) {
    				JsonElement arrayElement = sonJsonArray.get(i);
    				toXml(arrayElement, parentElement, name);
    			}
    		}else if (jsonElement instanceof JsonObject) {
    			//说明是一个json对象字符串,需要继续解析
    			JsonObject sonJsonObject = (JsonObject) jsonElement;
    			Element currentElement = null;
    			if (name != null) {
    				currentElement = parentElement.addElement(name);
    			}
    			Set<Entry<String, JsonElement>> set = sonJsonObject.entrySet();
    			for (Entry<String, JsonElement> s : set) {
    				toXml(s.getValue(), currentElement != null ? currentElement : parentElement, s.getKey());
    			}
    		} else {
    			//说明是一个键值对的key,可以作为节点插入了
    			addAttribute(parentElement, name, jsonElement.getAsString());
    		}
    		return parentElement;
    	}
    
    	/**
    	 * 
    	 * @param element  	父节点
    	 * @param name		子节点的名字
    	 * @param value		子节点的值
    	 */
    	public static void addAttribute(Element element, String name, String value) {
    		//增加子节点,并为子节点赋值
    		Element el = element.addElement(name);
    		el.addText(value);
    		
    	}
    	public static void main(String[] args) throws Exception {
    
    		Document document = DocumentHelper.createDocument();
    		Element root =  document.addElement("stakeapply"); //默认根节点
    		Element el = jsonToXml(STR_JSON, root);
    		System.out.println(el.asXML());
    		try {
    			//生成xml文件
    			String fileName = "test.xml";
    			OutputFormat format = OutputFormat.createPrettyPrint();
    			format.setEncoding("UTF-8"); // 指定XML编码
    			format.setExpandEmptyElements(true);//自动添加闭合标签
    			document.setXMLEncoding("UTF-8");
    			//指定文件路径,名字,格式
    			XMLWriter writer = new XMLWriter(
    					new FileOutputStream(new File("D:\\xml" + File.separator + fileName)), format);
    			writer.write(document);
    			writer.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    这就是一个小demo了,非常实用。楼主是http请求传入的json串,比较复杂,这里也把json和转化后的xml贴出来
    ```java
    /*
    json串
    {
        "stakeapply": {
            "voltageLevel": "AC00062", 
            "stakeList": {
                "stake": [
                    {
                        "stakeAssetNO": 45754745, 
                        "otherStakeTypeRemark": "xxx", 
                        "stationId": "547547547547"
                    }, 
                    {
                        "stakeAssetNO": 34325325322, 
                        "otherStakeTypeRemark": "xxx", 
                        "stationId": "52354645462"
                    }
                ]
            }, 
            "otherStationTypeRemark": "xxx", 
            "stationAddr": "哈哈", 
            "custLists": {
                "custList": {
                    "custId": "7547547547", 
                    "custPhone": 13666666666, 
                    "contactMode": 1
                }
            }, 
            "principalList": {
                "principal": [
                    {
                        "principalName": 121212, 
                        "principalType": 1
                    }, 
                    {
                        "principalName": 12121233, 
                        "principalType": 1
                    }
                ]
            }
        }
    }
    */
    
    /*
    转换后的xml
    <?xml version="1.0" encoding="UTF-8"?>
    
    <stakeapply>
      <voltageLevel>AC00062</voltageLevel>
      <stakeList>
        <stake>
          <stakeAssetNO>45754745</stakeAssetNO>
          <otherStakeTypeRemark>xxx</otherStakeTypeRemark>
          <stationId>547547547547</stationId>
        </stake>
        <stake>
          <stakeAssetNO>34325325322</stakeAssetNO>
          <otherStakeTypeRemark>xxx</otherStakeTypeRemark>
          <stationId>52354645462</stationId>
        </stake>
      </stakeList>
      <otherStationTypeRemark>xxx</otherStationTypeRemark>
      <stationAddr>哈哈</stationAddr>
      <custLists>
        <custList>
          <custId>7547547547</custId>
          <custPhone>13666666666</custPhone>
          <contactMode>1</contactMode>
        </custList>
      </custLists>
      <principalList>
        <principal>
          <principalName>121212</principalName>
          <principalType>1</principalType>
        </principal>
        <principal>
          <principalName>12121233</principalName>
          <principalType>1</principalType>
        </principal>
      </principalList>
    </stakeapply>
    */
    

     

    展开全文
  • Java json 转xml

    2017-06-02 16:36:12
    jar 下载: http://download.csdn.net/detail/capmiachael/9858840package com.as;import org.json.JSONObject; import org.json.XML;public class Test { public static void main(String[] args) { String jsonS

    jar 下载:
    http://download.csdn.net/detail/capmiachael/9858840

    package com.as;
    
    import org.json.JSONObject;
    import org.json.XML;
    
    public class Test {
    public static void main(String[] args) {
        String jsonString="{\"SALE_AMT1\":\"288\",\"SALE_AMT2\":\"288\",\"SALE_SO_ID\":\"X1000511G1705263645\",\"SALE_REAL_AMT\":\"288\",\"QTY\":\"1\",\"SALE_TOP_SO_ID\":\"X1000511G1705263645\",\"POS_ID\":\"G\",\"SALE_FLG\":\"销售\",\"SALE_STAFF\":\"100000\",\"DPET_ID\":\"100051\",\"CHECKOUT_DT\":\"2017-05-26 19:16:03\",\"REASON_NAME\":\"\",\"PROM_ID\":\"\",\"STD_PRICE\":\"288\",\"PROM_ID1\":\"\",\"ITEM_ID\":\"600000112\",\"PROM_NAME\":\"\",\"PROM_SET_SOT\":\"\"}";
        JSONObject json =new JSONObject(jsonString);
        String xml = XML.toString(json);
        System.out.println(xml);
    }
    
    }
    

    结果:

    <DPET_ID>100051</DPET_ID><POS_ID>G</POS_ID><PROM_ID1/><SALE_STAFF>100000</SALE_STAFF><PROM_ID/><STD_PRICE>288</STD_PRICE><ITEM_ID>600000112</ITEM_ID><SALE_AMT1>288</SALE_AMT1><SALE_SO_ID>X1000511G1705263645</SALE_SO_ID><SALE_AMT2>288</SALE_AMT2><CHECKOUT_DT>2017-05-26 19:16:03</CHECKOUT_DT><REASON_NAME/><SALE_FLG>销售</SALE_FLG><QTY>1</QTY><PROM_NAME/><SALE_TOP_SO_ID>X1000511G1705263645</SALE_TOP_SO_ID><SALE_REAL_AMT>288</SALE_REAL_AMT><PROM_SET_SOT/>

    附录 :各种语言的 均可在 http://json.org/ 找到

    展开全文
  • JAVA json转xml

    千次阅读 2017-05-24 17:17:17
    目前最新的是2.4的版本,json-lib还需要以下依赖包: 通过mvn库可以直接去下载。 jakartacommons-lang 2.5 jakartacommons-beanutils 1.8.0 jakartacom

    首先要去官方下载json-lib工具包
    https://mvnrepository.com/artifact/net.sf.json-lib/json-lib/2.4

    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
    </dependency>

    目前最新的是2.4的版本,json-lib还需要以下依赖包:
    通过mvn库可以直接去下载。
    jakartacommons-lang 2.5
    jakartacommons-beanutils 1.8.0
    jakartacommons-collections 3.2.1
    jakartacommons-logging 1.1.1
    ezmorph1.0.6

    这里写图片描述

    From JSON to XML

    Code
    XML output
    1.

        JSONObject json = new JSONObject( true );  
        String xml = XMLSerializer.write( json );  
      JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");  
    String xml = XMLSerializer.write( json );  
    JSONArray json = JSONArray.fromObject("[1,2,3]");  
    
    String xml = XMLSerializer.write( json ); 

    From XML to JSON

    Code

    1.    <a class="array">  
    2.      <e type="function" params="i,j">  
    3.          return matrix[i][j];  
    4.      </e>  
    5.    </a>  
    1.    JSONArray json = (JSONArray) XMLSerializer.read( xml );  
    2.    System.out.println( json );  
    3.    // prints [function(i,j){ return matrix[i][j]; }]  

    自己示例:

    public String segmentXml(String text) {
       JSONObject jsonObjec =segmentJson(text);
       String xml = json2XML(jsonObjec.toString());
       return  xml;
    }
    展开全文
  • 参考:http://heipark.iteye.com/blog/1394844需要json-lib-2.1-jdk15.jar和xom-1.2.5.jar,maven pom.xml如下:xml代码net.sf.json-libjson-lib2.1jdk15xomxom1.2.5jarcompilejava代码package ...

    参考:http://heipark.iteye.com/blog/1394844

    需要json-lib-2.1-jdk15.jar和xom-1.2.5.jar,maven pom.xml如下:

    xml代码

    net.sf.json-lib

    json-lib

    2.1

    jdk15

    xom

    xom

    1.2.5

    jar

    compile

    java代码

    package com.nirvanainfo.salesleads.framework.utils;

    import java.io.ByteArrayOutputStream;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.Iterator;

    import java.util.List;

    import java.util.Map;

    import net.sf.json.JSON;

    import net.sf.json.JSONSerializer;

    import net.sf.json.xml.XMLSerializer;

    import org.dom4j.Document;

    import org.dom4j.DocumentHelper;

    import org.dom4j.Element;

    import org.dom4j.io.OutputFormat;

    import org.dom4j.io.XMLWriter;

    /**

    * Created by Administrator on 2016/9/2.

    */

    public class XmlConverUtil {

    /**

    * map to xml xml value1

    * label="key2">value2

    ......

    *

    * @param map

    * @return

    */

    public static String maptoXml(Map map) {

    Document document = DocumentHelper.createDocument();

    Element nodeElement = document.addElement("node");

    for (Object obj : map.keySet()) {

    Element keyElement = nodeElement.addElement("key");

    keyElement.addAttribute("label", String.valueOf(obj));

    keyElement.setText(String.valueOf(map.get(obj)));

    }

    return doc2String(document);

    }

    /**

    * list to xml xml value1

    * label="key2">value2

    ......

    * label="key1">value1

    * label="key2">value2

    ......

    *

    * @param list

    * @return

    */

    public static String listtoXml(List list) throws Exception {

    Document document = DocumentHelper.createDocument();

    Element nodesElement = document.addElement("nodes");

    int i = 0;

    for (Object o : list) {

    Element nodeElement = nodesElement.addElement("node");

    if (o instanceof Map) {

    for (Object obj : ((Map) o).keySet()) {

    Element keyElement = nodeElement.addElement("key");

    keyElement.addAttribute("label", String.valueOf(obj));

    keyElement.setText(String.valueOf(((Map) o).get(obj)));

    }

    } else {

    Element keyElement = nodeElement.addElement("key");

    keyElement.addAttribute("label", String.valueOf(i));

    keyElement.setText(String.valueOf(o));

    }

    i++;

    }

    return doc2String(document);

    }

    /**

    * json to xml {"node":{"key":{"@label":"key1","#text":"value1"}}} conver

    *

    * label="key1">value1

    *

    * @param json

    * @return

    */

    public static String jsontoXml(String json) {

    try {

    XMLSerializer serializer = new XMLSerializer();

    JSON jsonObject = JSONSerializer.toJSON(json);

    return serializer.write(jsonObject);

    } catch (Exception e) {

    e.printStackTrace();

    }

    return null;

    }

    /**

    * xml to map xml value1

    * label="key2">value2

    ......

    *

    * @param xml

    * @return

    */

    public static Map xmltoMap(String xml) {

    try {

    Map map = new HashMap();

    Document document = DocumentHelper.parseText(xml);

    Element nodeElement = document.getRootElement();

    List node = nodeElement.elements();

    for (Iterator it = node.iterator(); it.hasNext();) {

    Element elm = (Element) it.next();

    map.put(elm.attributeValue("label"), elm.getText());

    elm = null;

    }

    node = null;

    nodeElement = null;

    document = null;

    return map;

    } catch (Exception e) {

    e.printStackTrace();

    }

    return null;

    }

    /**

    * xml to list xml value1

    * label="key2">value2

    ......

    * label="key1">value1

    * label="key2">value2

    ......

    *

    * @param xml

    * @return

    */

    public static List xmltoList(String xml) {

    try {

    List list = new ArrayList();

    Document document = DocumentHelper.parseText(xml);

    Element nodesElement = document.getRootElement();

    List nodes = nodesElement.elements();

    for (Iterator its = nodes.iterator(); its.hasNext();) {

    Element nodeElement = (Element) its.next();

    Map map = xmltoMap(nodeElement.asXML());

    list.add(map);

    map = null;

    }

    nodes = null;

    nodesElement = null;

    document = null;

    return list;

    } catch (Exception e) {

    e.printStackTrace();

    }

    return null;

    }

    /**

    * xml to json value1 转化为

    * {"key":{"@label":"key1","#text":"value1"}}

    *

    * @param xml

    * @return

    */

    public static String xmltoJson(String xml) {

    XMLSerializer xmlSerializer = new XMLSerializer();

    return xmlSerializer.read(xml).toString();

    }

    /**

    *

    * @param document

    * @return

    */

    public static String doc2String(Document document) {

    String s = "";

    try {

    // 使用输出流来进行转化

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    // 使用UTF-8编码

    OutputFormat format = new OutputFormat(" ", true, "UTF-8");

    XMLWriter writer = new XMLWriter(out, format);

    writer.write(document);

    s = out.toString("UTF-8");

    } catch (Exception ex) {

    ex.printStackTrace();

    }

    return s;

    }

    }

    展开全文
  • http://www.verejava.com/?id=16998704382152下载依赖 jar 包json.jardom4j-1.6.1.jarjaxen-1.1-beta-6.jarproduct.xml1电脑24000package com.json19;import java.io.File;import java.util.ArrayList;import java....
  • java json 转xml xml转json

    2019-08-04 13:26:21
    json转xml字符串 xml转json 调用 引入jar 日志 code https://download.csdn.net/download/weixin_42749765/11470681 依赖 <dependency> <groupId>dom4j</groupId> ...
  • 我有一个程序可以从json对象生成xml。String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";JSON json = JSONSerializer.toJSON( str );XMLSerializer ...
  • 结果xml截图 json数据 main启动 import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public static void main(String[] args) { // 本地读取方式 new xxx()....
  • import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;import java.util.Iterator;import java.util.Map;import java.util.Set;/*** The type Test.*/p...
  • 我们可以使用org.json.XML类将JSONObject转换为XML格式,这提供了将XML文本转换为JSONObject并将JSONObject转换为XML文本的静态方法。 XML.toString()方法转换JSON对象成合式,元件正常XML字符串。语法...
  • 现在互联网上,最流行的两大传输数据的标准就是jsonXML了,关于谁是最好的,一直以来都是人们争论的话题,其实各有各的缺点和优点;1.定义介绍(1).XML定义扩展标记语言 (Extensible Markup Language, XML) ,用于...
  • 依赖的包:json-lib-2.4-jdk15.jarezmorph-1.0.6.jarxom-1.2.1.jarcommons-lang-2.1.jarcommons-io-1.3.2.jarjaxen-1.1.jar输入xml文件,输出JSON对象package com.cash.util;import java.io.IOException;import java....
  • import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;impo...
  • 依赖的包:json-lib-2.4-jdk15.jarezmorph-1.0.6.jarxom-1.2.1.jarcommons-lang-2.1.jarcommons-io-1.3.2.jarjaxen-1.1.jar输入xml文件,输出JSON对象package com.cash.util;import java.io.IOException;import java....
  • 看到一个json字符串和xml工具类感觉挺好用的xml转json org.jdom用 dom 提取节点 成mapjson xml com.alibaba.fastjson.JSONObject遍历key代码如下import java.io.File;import java.io.IOException;import ...
  • 项目封装了新的SDK,需要对SDK进行测试,API没有变更。设计一自动化CASE:通过openapi的方式调用YAPI上接口测试用例,返回结果A;...但是返回结果中xmlJson的属性顺序不一定相对,所以用基本的...
  • 优质好文、感谢点个再看、分享本文原创作者bigsai(同公众号),本文以浅显易懂的方式给大家讲解自己所认知的json,如果有错误或者不准确地方还请大家给出指正,另外本文以关卡课程的方式在博学谷也是开放的,大家也可...
  • 优质文章,第一时间送达上一篇:这300G的Java资料是我师傅当年给我的,免费分享给大家下一篇:这200G的Java实战资料是我师傅当年教我的第二招作者:布加迪编译来源:51CTO(点击阅读全文前往)众所周知,JSON让开发...
  • 谁拔得头筹?谁又落于人后?我们分析了 GitHub 中 47,251 条依赖关系,得出最受欢迎的...我们分析了 GitHub 中前3862个 Java 项目里用到的12059个不同 Java 库的47251条导入声明。从该列表中,我们选取了排名前100的...
  • 谁拔得头筹?谁又落于人后?我们分析了 GitHub 中 47,251 条依赖关系,得出最受欢迎的100个 ...我们分析了 GitHub 中前3862个 Java 项目里用到的12059个不同 Java 库的47251条导入声明。从该列表中,我们选取了排名...
  • 百度:java json 类库,以后打算统一用jackson,package xml2json;import java.io.File;import java.util.Map;import org.apache.commons.io.FileUtils;import org.codehaus.jackson.map.ObjectMapper;import org....
  • js xml转json,json转xml 在线XML转JSON,JSON转XML-BeJSON.comhttp://www.bejson.com/xml2json/ ------------------------------------------------------------------------------代码 package xml2json; ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,982
精华内容 1,192
关键字:

javajson转xml

java 订阅