Java - 将 JSON 转换为 XML 并保持属性

标签 java json xml

使用 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 属性?

最佳答案

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

import com.github.underscore.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"
// }

关于Java - 将 JSON 转换为 XML 并保持属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38002128/

相关文章:

asp.net - 多环境.NET Core

javascript - ajax - 将数据作为 json 发送到 php 服务器并接收响应

python - 使用 Beautiful Soup 解析 HTML 中的数据绑定(bind)标签

python - lxml xsi :schemaLocation namespace URI validation issue

xml - vb.net-从XSD创建类并生成xml

java - Nutch API 建议

java - 如何让每个SQL查询都是一个线程?

java - 具有两个参数的方法,这两个参数都需要双重分派(dispatch)

Java - 为什么迭代器需要通用?

xml - 将多个 xml 元素值添加到列表中