JSON 到 XML 转换的 Java 实现 [已关闭]

2022-09-02 02:50:19

是否有现有的 JAR 可用于从 JSON 转换为 XML?


答案 1

您可以创建一个 JSONObject,然后使用 org.json 命名空间中的 XML 类将其转换为 XML

将 json 字符串包装在对象中就像在它的构造函数中传递它一样简单

JSONObject o = new JSONObject(jsonString);

然后,您可以使用 XML 类以 XML 格式获取它,如下所示:

String xml = org.json.XML.toString(o);

答案 2

不是 Java,而是纯 XSLT 2.0 实现

看看FXSL 2.x库中f:json-document()。

使用此功能,非常容易合并JSon并像...XML.

例如,可以只编写以下 XPath 表达式:

f:json-document($vstrParam)/Students/*[sex = 'Female']

并让所有有性别的学生的孩子=“女”

下面是完整的示例:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:f="http://fxsl.sf.net/"
 exclude-result-prefixes="f xs"
 >
 <xsl:import href="../f/func-json-document.xsl"/>

 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vstrParam" as="xs:string">
{

  "teacher":{
    "name":
      "Mr Borat",
    "age":
      "35",
    "Nationality":
      "Kazakhstan"
             },


  "Class":{
    "Semester":
      "Summer",
    "Room":
      null,
    "Subject":
      "Politics",
    "Notes":
      "We're happy, you happy?"
           },

  "Students":
    {
      "Smith":
        {"First Name":"Mary","sex":"Female"},
      "Brown":
        {"First Name":"John","sex":"Male"},
      "Jackson":
        {"First Name":"Jackie","sex":"Female"}
    }
    ,


  "Grades":

    {
      "Test":
      [
        {"grade":"A","points":68,"grade":"B","points":25,"grade":"C","points":15},

        {"grade":"C","points":2, "grade":"B","points":29, "grade":"A","points":55},

        {"grade":"C","points":2, "grade":"A","points":72, "grade":"A","points":65}
       ]
    }


}
 </xsl:variable>

 <xsl:template match="/">
    <xsl:sequence select=
     "f:json-document($vstrParam)/Students/*[sex = 'Female']"/>

 </xsl:template>
</xsl:stylesheet>

当上述转换应用于任何 XML 文档(忽略)时,将生成正确的结果

<Smith>
   <First_Name>Mary</First_Name>
   <sex>Female</sex>
</Smith>
<Jackson>
   <First_Name>Jackie</First_Name>
   <sex>Female</sex>
</Jackson>