Java实现JSON到XML的转换

时间:2009-02-18 00:03:49

标签: java xml json translation

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

9 个答案:

答案 0 :(得分:25)

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

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

JSONObject o = new JSONObject(jsonString);

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

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

答案 1 :(得分:14)

不是Java,而是纯XSLT 2.0实现

查看f:json-document()中的FXSL 2.x library

使用此函数非常容易合并JSon并将其用作... XML。

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

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

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>

答案 2 :(得分:3)

另一种可能性:Jettison,http://jettison.codehaus.org可以通过XML解析接口(stax XMLStreamReader)公开Json,它允许与只理解XML的系统集成。它需要使用一个约定(badgerfish,或其他任何一个叫做)。

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

但问题本身有点模糊:虽然你总是可以从一个转换到另一个(这真的是一件非常简单的事情),XML和JSON并不等同:没有一对一的无损泛型映射。 因此,问题是:您打算如何处理结果,如何使用xml?

答案 3 :(得分:2)

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

答案 4 :(得分:2)

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

  • 以上关于没有完全万无一失的一对一映射的要点是有效的,但我已经有了使用上述库将xml转换为json的良好体验。

答案 5 :(得分:1)

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

答案 6 :(得分:1)

Conversion Box!!!

我正在使用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();
    }
}
}

输出:

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>

答案 7 :(得分:0)

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

答案 8 :(得分:0)

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

这是一个简单的例子:

输入文件:

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

导入+代码:

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();

输出:

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