【问题标题】:How to convert a xml file to json string and back keeping attributes如何将 xml 文件转换为 json 字符串并保留属性
【发布时间】:2014-04-29 16:32:36
【问题描述】:

我正在尝试将 xml 文件转换为 json 并向后转换,但是这样做时完整性会发生变化,来自:

<option value="0"> <!--something--> </option>

<option> <!--something--> <value>0</value> </option>

我在使用 org.json 时得到了这个,是否有另一个 json 库可以在保持文件完整性的同时完成这项工作?

【问题讨论】:

  • 由于 JSON 没有属性的概念,这听起来很复杂。 JSON 到 XML 的转换如何知道应该将哪个 JSON 属性转换为 XML 属性以及应该将哪个属性转换为 XML 元素?

标签: java xml json org.json


【解决方案1】:

XML 转 Json

import net.sf.json.JSONObject; 
import org.json.JSONObject;.  

    public class Main {

            public static int PRETTY_PRINT_INDENT_FACTOR = 4;
            public static String TEST_XML_STRING ="ur xml";

            public static void main(String[] args) {
                try {
                    JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
                    String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
                    System.out.println(jsonPrettyPrintString);
                } catch (JSONException je) {
                    System.out.println(je.toString());
                }
            }
        }

json 到 xml:

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

public class jsontoxml {
    public static void main(String[] args) throws JSONException {
    String str="ur json here";  
        JSONObject json = new JSONObject(str);
        String xml = XML.toString(json);
            System.out.println(xml);            
    }

} 

【讨论】:

    【解决方案2】:

    有一个带有静态方法U.xmlToJson(xml)underscore-java 库。

    <option value="0">
      <!--something-->
    </option>
    

    输出:

    {
      "option": {
        "-value": "0",
        "#comment": "something"
      },
      "#omit-xml-declaration": "yes"
    }
    

    【讨论】:

    • 确实这应该是公认的答案。 json.org 的 JSON 库将 xml 属性转换为节点,Jackson 的实现不处理混合内容。这个库为我解决了这两个问题。干得好!
    猜你喜欢
    • 2016-10-26
    • 2018-07-23
    • 2017-04-20
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多