Java实现JSON到XML的转换

时间:2021-01-17 20:41:49

Are there existing JARs available to convert from JSON to XML?

是否存在可以从JSON转换为XML的现有jar ?

9 个解决方案

#1


14  

Not a Java, but a pure XSLT 2.0 implementation:

不是Java,而是纯粹的XSLT 2.0实现:

Have a look at the f:json-document() from the FXSL 2.x library.

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

Using this function it is extremely easy to incorporate JSon and use it just as... XML.

使用这个函数,很容易合并JSon并将其用作……XML。

For example, one can just write the following XPath expression:

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

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

and get all children of Students with sex = 'Female'

让所有学生的孩子都有性行为=“女性”

Here is the complete example:

这里有一个完整的例子:

<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>

When the above transformation is applied on any XML document (ignored), the correct result is produced:

当上述转换应用于任何XML文档(被忽略)时,都会产生正确的结果:

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

#2


25  

You can create a JSONObject, and then convert it to XML using the XML class in the org.json namespace

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

Wrapping the json string in the object is as easy as passing it in its constructor

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

JSONObject o = new JSONObject(jsonString);

Then you can get it in XML format using the XML class, like so:

然后您可以使用XML类的XML格式获取它:

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

#3


3  

One more possibility: Jettison, http://jettison.codehaus.org can expose Json via XML parsing interface (stax XMLStreamReader), which allows integration with systems that only understand XML. It requires use of a convention (badgerfish, or whatever the other one was called).

还有一种可能:Jettison, http://jettison.codehaus.org可以通过XML解析接口(stax XMLStreamReader)公开Json,它允许与只理解XML的系统集成。它需要使用约定(badgerfish,或者其他被称为约定的东西)。

XStream, for example, uses Jettison (or at least Badgerfish convention) to allow use of JSON.

例如,XStream使用了Jettison(或者至少是Badgerfish约定)来允许使用JSON。

But the question itself is bit vague: while you can always convert from one to the othe (it is a very trivial thing to do really), XML and JSON are not equivalent: there is no one-to-one lossless generic mapping. Hence, the question is: what are you planning to do with results, how is resulting xml to be used?

但是问题本身有点模糊:尽管您总是可以将一个映射转换为othe(这确实是一件非常琐碎的事情),但XML和JSON并不是等价的:没有一对一的无损的泛型映射。因此,问题是:您打算如何处理结果,如何使用生成的xml ?

#4


2  

http://json-lib.sourceforge.net/

http://json-lib.sourceforge.net/

  • the points above about no completely foolproof one-one mapping are valid, but I have had a good experience with converting xml to json using the above library.
  • 上面关于没有绝对可靠的一对一映射的要点是有效的,但是我有很好的经验,可以使用上面的库将xml转换成json。

#5


2  

You may want to try XStream. Take a look at http://x-stream.github.io/faq.html#JSON.

您可能想尝试XStream。看看http://x-stream.github.io/faq.html#JSON。

#6


1  

You can try https://github.com/lukas-krecan/json2xml that provides simple JSON to XML conversion. It takes Jackson JSON parser and usees it to emit SAX events.

您可以尝试https://github.com/lukas-krecan/json2xml,它提供简单的JSON到XML转换。它使用Jackson JSON解析器并使用它来发出SAX事件。

#7


1  

Conversion Box!!!

转换盒! ! !

I am using the JSON that Dimitre has pasted in his reply and have converted into an XML. Lets see if it works for you .....

我正在使用Dimitre在他的回复中粘贴的JSON,并将其转换为XML。让我看看它是否适合你……

import org.json.me.JSONObject;

import cjm.component.cb.xml.ToXML;

public class Test
{
public static void main(String[] args)
{
    try
    {
        JSONObject objectJSON = new JSONObject();

        objectJSON.put("ROOT", (new JSONObject("{\"teacher\":{\"name\":\"Mr Borat\",\"age\":\"35\",\"Nationality\":\"Kazakhstan\"},\"Class\":{\"Semester\":\"Summer\",\"Room\":null,\"Subject\":\"Politics\",\"Notes\":\"We're happy, you happy?\"},\"Students\":{\"Smith\":{\"FirstName\":\"Mary\",\"sex\":\"Female\"},\"Brown\":{\"FirstName\":\"John\",\"sex\":\"Male\"},\"Jackson\":{\"FirstName\":\"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}]}}")));

        System.out.println("JSON: " + objectJSON);

        StringBuilder xml = new ToXML().convertToXML(objectJSON, true); // Conversion Box!!!!

        System.out.println("XML: " + xml);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

Output:

输出:

JSON: {"ROOT":{"Students":{"Brown":{"FirstName":"John","sex":"Male"},"Jackson":{"FirstName":"Jackie","sex":"Female"},"Smith":{"FirstName":"Mary","sex":"Female"}},"Class":{"Subject":"Politics","Room":null,"Semester":"Summer","Notes":"We're happy, you happy?"},"Grades":{"Test":[{"points":15,"grade":"C"},{"points":55,"grade":"A"},{"points":65,"grade":"A"}]},"teacher":{"age":"35","name":"Mr Borat","Nationality":"Kazakhstan"}}}
 -------- JSON Detected -------- 
 -------- XML created Successfully -------- 
XML: <ROOT><Students><Brown><FirstName>John</FirstName><sex>Male</sex></Brown><Jackson><FirstName>Jackie</FirstName><sex>Female</sex></Jackson><Smith><FirstName>Mary</FirstName><sex>Female</sex></Smith></Students><Class><Subject>Politics</Subject><Room>null</Room><Semester>Summer</Semester><Notes>We're happy, you happy?</Notes></Class><Grades><Test><LIST_ELEMENT_Test><points>15</points><grade>C</grade></LIST_ELEMENT_Test><LIST_ELEMENT_Test><points>55</points><grade>A</grade></LIST_ELEMENT_Test><LIST_ELEMENT_Test><points>65</points><grade>A</grade></LIST_ELEMENT_Test></Test></Grades><teacher><age>35</age><name>Mr Borat</name><Nationality>Kazakhstan</Nationality></teacher></ROOT>

#8


0  

StAXON can convert JSON to XML using either XSLT with default templates or StAX event API https://github.com/beckchr/staxon/wiki/Converting-JSON-to-XML

StAXON可以使用带有默认模板的XSLT将JSON转换为XML,也可以使用StAX事件API https://github.com/beckchr/staxon/wiki/Converting-JSON-to-XML

Here's a simple example:

这是一个简单的例子:

INPUT FILE:

输入文件:

{
    "container":[
        {
            "someString":"xxxxx",
            "someInteger":123,
            "someArrayElem":[
                {
                    "key":1111,
                    "value":"One"
                },
                {
                    "key":2222,
                    "value":"Two"
                }
            ]
        }
    ]
}

Imports + code:

进口+代码:

import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import java.io.StringWriter;

StringWriter stringWriter = new StringWriter();
JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).prettyPrint(false).build();
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(getClass().getClassLoader().getResourceAsStream("input.json"));
XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(stringWriter);
writer = new PrettyXMLEventWriter(writer);
writer.add(reader);
String xml = stringWriter.getBuffer().toString();

OUTPUT:

输出:

<?xml version="1.0" encoding="UTF-8"?>
<container>
    <someString>xxxxx</someString>
    <someInteger>123</someInteger>
    <someArrayElem>
        <key>1111</key>
        <value>One</value>
    </someArrayElem>
    <someArrayElem>
        <key>2222</key>
        <value>Two</value>
    </someArrayElem>
</container>

#9


0  

You can use json-lib, it provides bidirectional conversion.

您可以使用json-lib,它提供双向转换。

#1


14  

Not a Java, but a pure XSLT 2.0 implementation:

不是Java,而是纯粹的XSLT 2.0实现:

Have a look at the f:json-document() from the FXSL 2.x library.

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

Using this function it is extremely easy to incorporate JSon and use it just as... XML.

使用这个函数,很容易合并JSon并将其用作……XML。

For example, one can just write the following XPath expression:

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

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

and get all children of Students with sex = 'Female'

让所有学生的孩子都有性行为=“女性”

Here is the complete example:

这里有一个完整的例子:

<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>

When the above transformation is applied on any XML document (ignored), the correct result is produced:

当上述转换应用于任何XML文档(被忽略)时,都会产生正确的结果:

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

#2


25  

You can create a JSONObject, and then convert it to XML using the XML class in the org.json namespace

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

Wrapping the json string in the object is as easy as passing it in its constructor

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

JSONObject o = new JSONObject(jsonString);

Then you can get it in XML format using the XML class, like so:

然后您可以使用XML类的XML格式获取它:

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

#3


3  

One more possibility: Jettison, http://jettison.codehaus.org can expose Json via XML parsing interface (stax XMLStreamReader), which allows integration with systems that only understand XML. It requires use of a convention (badgerfish, or whatever the other one was called).

还有一种可能:Jettison, http://jettison.codehaus.org可以通过XML解析接口(stax XMLStreamReader)公开Json,它允许与只理解XML的系统集成。它需要使用约定(badgerfish,或者其他被称为约定的东西)。

XStream, for example, uses Jettison (or at least Badgerfish convention) to allow use of JSON.

例如,XStream使用了Jettison(或者至少是Badgerfish约定)来允许使用JSON。

But the question itself is bit vague: while you can always convert from one to the othe (it is a very trivial thing to do really), XML and JSON are not equivalent: there is no one-to-one lossless generic mapping. Hence, the question is: what are you planning to do with results, how is resulting xml to be used?

但是问题本身有点模糊:尽管您总是可以将一个映射转换为othe(这确实是一件非常琐碎的事情),但XML和JSON并不是等价的:没有一对一的无损的泛型映射。因此,问题是:您打算如何处理结果,如何使用生成的xml ?

#4


2  

http://json-lib.sourceforge.net/

http://json-lib.sourceforge.net/

  • the points above about no completely foolproof one-one mapping are valid, but I have had a good experience with converting xml to json using the above library.
  • 上面关于没有绝对可靠的一对一映射的要点是有效的,但是我有很好的经验,可以使用上面的库将xml转换成json。

#5


2  

You may want to try XStream. Take a look at http://x-stream.github.io/faq.html#JSON.

您可能想尝试XStream。看看http://x-stream.github.io/faq.html#JSON。

#6


1  

You can try https://github.com/lukas-krecan/json2xml that provides simple JSON to XML conversion. It takes Jackson JSON parser and usees it to emit SAX events.

您可以尝试https://github.com/lukas-krecan/json2xml,它提供简单的JSON到XML转换。它使用Jackson JSON解析器并使用它来发出SAX事件。

#7


1  

Conversion Box!!!

转换盒! ! !

I am using the JSON that Dimitre has pasted in his reply and have converted into an XML. Lets see if it works for you .....

我正在使用Dimitre在他的回复中粘贴的JSON,并将其转换为XML。让我看看它是否适合你……

import org.json.me.JSONObject;

import cjm.component.cb.xml.ToXML;

public class Test
{
public static void main(String[] args)
{
    try
    {
        JSONObject objectJSON = new JSONObject();

        objectJSON.put("ROOT", (new JSONObject("{\"teacher\":{\"name\":\"Mr Borat\",\"age\":\"35\",\"Nationality\":\"Kazakhstan\"},\"Class\":{\"Semester\":\"Summer\",\"Room\":null,\"Subject\":\"Politics\",\"Notes\":\"We're happy, you happy?\"},\"Students\":{\"Smith\":{\"FirstName\":\"Mary\",\"sex\":\"Female\"},\"Brown\":{\"FirstName\":\"John\",\"sex\":\"Male\"},\"Jackson\":{\"FirstName\":\"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}]}}")));

        System.out.println("JSON: " + objectJSON);

        StringBuilder xml = new ToXML().convertToXML(objectJSON, true); // Conversion Box!!!!

        System.out.println("XML: " + xml);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

Output:

输出:

JSON: {"ROOT":{"Students":{"Brown":{"FirstName":"John","sex":"Male"},"Jackson":{"FirstName":"Jackie","sex":"Female"},"Smith":{"FirstName":"Mary","sex":"Female"}},"Class":{"Subject":"Politics","Room":null,"Semester":"Summer","Notes":"We're happy, you happy?"},"Grades":{"Test":[{"points":15,"grade":"C"},{"points":55,"grade":"A"},{"points":65,"grade":"A"}]},"teacher":{"age":"35","name":"Mr Borat","Nationality":"Kazakhstan"}}}
 -------- JSON Detected -------- 
 -------- XML created Successfully -------- 
XML: <ROOT><Students><Brown><FirstName>John</FirstName><sex>Male</sex></Brown><Jackson><FirstName>Jackie</FirstName><sex>Female</sex></Jackson><Smith><FirstName>Mary</FirstName><sex>Female</sex></Smith></Students><Class><Subject>Politics</Subject><Room>null</Room><Semester>Summer</Semester><Notes>We're happy, you happy?</Notes></Class><Grades><Test><LIST_ELEMENT_Test><points>15</points><grade>C</grade></LIST_ELEMENT_Test><LIST_ELEMENT_Test><points>55</points><grade>A</grade></LIST_ELEMENT_Test><LIST_ELEMENT_Test><points>65</points><grade>A</grade></LIST_ELEMENT_Test></Test></Grades><teacher><age>35</age><name>Mr Borat</name><Nationality>Kazakhstan</Nationality></teacher></ROOT>

#8


0  

StAXON can convert JSON to XML using either XSLT with default templates or StAX event API https://github.com/beckchr/staxon/wiki/Converting-JSON-to-XML

StAXON可以使用带有默认模板的XSLT将JSON转换为XML,也可以使用StAX事件API https://github.com/beckchr/staxon/wiki/Converting-JSON-to-XML

Here's a simple example:

这是一个简单的例子:

INPUT FILE:

输入文件:

{
    "container":[
        {
            "someString":"xxxxx",
            "someInteger":123,
            "someArrayElem":[
                {
                    "key":1111,
                    "value":"One"
                },
                {
                    "key":2222,
                    "value":"Two"
                }
            ]
        }
    ]
}

Imports + code:

进口+代码:

import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import java.io.StringWriter;

StringWriter stringWriter = new StringWriter();
JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).prettyPrint(false).build();
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(getClass().getClassLoader().getResourceAsStream("input.json"));
XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(stringWriter);
writer = new PrettyXMLEventWriter(writer);
writer.add(reader);
String xml = stringWriter.getBuffer().toString();

OUTPUT:

输出:

<?xml version="1.0" encoding="UTF-8"?>
<container>
    <someString>xxxxx</someString>
    <someInteger>123</someInteger>
    <someArrayElem>
        <key>1111</key>
        <value>One</value>
    </someArrayElem>
    <someArrayElem>
        <key>2222</key>
        <value>Two</value>
    </someArrayElem>
</container>

#9


0  

You can use json-lib, it provides bidirectional conversion.

您可以使用json-lib,它提供双向转换。