Java/Scala - 将 xml 转换为 json

标签 java json xml scala

我想使用 Java 或 Scala 将 XML 转换为 JSON。下面是工作代码,但在这里我看不到 Json 中 XML 属性的任何标识符来区分它与元素。 我需要帮助来获取 Json 输出中带有标识符 (@) 的 XML 属性。

输入 XML:

      <Test>
        <AttrTest Code="199" Pro="Intel"  Version="9.106">
            <Info>FD2F</Info>
        </AttrTest>
      </Test>

代码:

    import org.json.XML
            def xmlToJson(xml: String) = {
              var PRETTY_PRINT_INDENT_FACTOR = 4
              try {
                val xmlJSONObj = XML.toJSONObject(xml)
                val jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR)
                jsonPrettyPrintString
              } catch {
                case ex: Exception =>
                  println(ex.toString)
              }
            }

           val xmlStr = "<Test>\n\t\t<AttrTest Code=\"199\" Pro=\"Intel\"  Version=\"9.106\">\n\t\t<Info>FD2F</Info>\n</AttrTest>\n</Test>\n\t"
            println(xmlToJson(xmlStr))

输出:

        {"Test": {"AttrTest": {
            "Version": 9.106,
            "Pro": "Intel",
            "Info": "FD2F",
            "Code": 199
        }}}

预期输出:

        {"Test": {"AttrTest": {
            "@Version": 9.106,
            "@Pro": "Intel",
            "Info": "FD2F",
            "@Code": 199
        }}}

请帮忙。

最佳答案

恐怕您正在使用的库无法实现这一点。以下是他们的文档:

Some information may be lost in this transformation because JSON is a data format and XML is a document format. XML uses elements, attributes, and content text, while JSON uses unordered collections of name/value pairs and arrays of values. JSON does not does not like to distinguish between elements and attributes.

您可以尝试查看其他 XML->JSON 库或实现预转换步骤,例如,向每个节点的属性附加“@”前缀。

关于Java/Scala - 将 xml 转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62194982/

相关文章:

java - 无法定位当前 GPS 位置

java - 计算所有字符序列

java - 一些字符(例如括号)将在 Spring @RequestBody 中进行编码。如何解码它们?

php - Google Adwords API 报告实用程序 - PHP - XML 无效?

java - DOCX4J 变量准备在打开保存的 docx 时造成麻烦

java - 为 ClassLoader getResourceAsStream() 使用绝对路径

java - 如何生成具有外键属性的通用 CriteriaQuery?

php - 为什么我将 json 的显示加倍

javascript - Ruby on Rails 生成 Json

c# - 绑定(bind)手势识别器