【问题标题】:Java - Convert JSON to XML keeping the attributesJava - 将 JSON 转换为 XML,保留属性
【发布时间】:2016-10-26 09:47:41
【问题描述】:

使用 org.json json 库,可以轻松地将 XML 转换为 JSON。但是转换回 XML 总是将 JSON 属性转换为 XML 节点:

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

public class Test {
    public static void main(String[] args) throws Exception {
        String xml = "<tag1 attr1=\"val1\"><tag2 attr2=\"val2\"/></tag1>";
        System.out.println(xml);

        JSONObject str = XML.toJSONObject(xml);
        System.out.println(str);

        JSONObject json = new JSONObject(str.toString());
        String xml2 = XML.toString(json);
        System.out.println(xml2);
    }
}

输出

<tag1 attr1="val1"><tag2 attr2="val2"/></tag1>
{"tag1":{"attr1":"val1","tag2":{"attr2":"val2"}}}
<tag1><attr1>val1</attr1><tag2><attr2>val2</attr2></tag2></tag1>

如何检索我的 XML 属性?

【问题讨论】:

  • 你看过Badgerfish吗?这是将 XML 转换为 JSON 并再次转换回来的约定。如果您不介意 JSON 中有奇怪之处,可能对您有用。

标签: java json xml


【解决方案1】:

如果您要在 XML 以下进行转换

<tag1><attr1>val1</attr1><tag2><attr2>val2</attr2></tag2></tag1> 

你会得到相同的 JSON 结果;

{"tag1":{"attr1":"val1","tag2":{"attr2":"val2"}}}

因此从 JSON 转换回 XML 可能会导致歧义。因此最好编写一些自定义代码来指示一个 json 字段和一个属性或标签。我不确定是否有用于该转换的库,但此链接可能会有所帮助;

http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html

【讨论】:

    【解决方案2】:

    Underscore-java 具有静态方法 U.xmlToJson(xml)U.jsonToXml(json)Live example

    import com.github.underscore.lodash.U;
    
    public class Test {
        public static void main(String[] args) {
            String xml = "<tag1 attr1=\"val1\"><tag2 attr2=\"val2\"/></tag1>";
            System.out.println(U.xmlToJson(xml));
            System.out.println(U.jsonToXml(U.xmlToJson(xml)));
        }
    }
    
    // {
    //   "tag1": {
    //     "-attr1": "val1",
    //     "tag2": {
    //       "-attr2": "val2",
    //       "-self-closing": "true"
    //     }
    //   },
    //   "#omit-xml-declaration": "yes"
    // }
    

    【讨论】:

      猜你喜欢
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2014-04-29
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 2019-01-04
      相关资源
      最近更新 更多