如何仅使用Jackson将XML转换为JSON?

时间:2022-04-24 21:50:14

I am getting a response from server as XML. But I need to display this in JSON format.

我从服务器获得XML响应。但我需要以JSON格式显示它。

Is there any way to convert it without any third party API? I used Jackson but for this I need to create POJO.

有没有办法在没有任何第三方API的情况下进行转换?我用过杰克逊,但为此我需要创建POJO。

The response from server is like this:

服务器的响应是这样的:

<?xml version='1.0'?>
<errors><error><status>400</status><message>The field 'quantity' is invalid.</message><details><invalid_reason>The quantity specified is greater than the quantity of the product that is available to ship.</invalid_reason><available_quantity>0</available_quantity><order_product_id>12525</order_product_id></details></error></errors>

3 个解决方案

#1


12  

Using Jackson 2.x

You can do that with Jackson and no POJOs are required for that:

你可以用Jackson做到这一点,并且不需要POJO:

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
             "<errors>\n" +
             "  <error>\n" +
             "    <status>400</status>\n" +
             "    <message>The field 'quantity' is invalid.</message>\n" +
             "    <details>\n" +
             "      <invalid_reason>The quantity specified is greater than the quantity of the product that is available to ship.</invalid_reason>\n" +
             "      <available_quantity>0</available_quantity>\n" +
             "      <order_product_id>12525</order_product_id>\n" +
             "    </details>\n" +
             "  </error>\n" +
             "</errors>";

XmlMapper xmlMapper = new XmlMapper();
JsonNode node = xmlMapper.readTree(xml.getBytes());

ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node);

The following dependencies are required:

需要以下依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.8.2</version>
</dependency>

Be aware of the XmlMapper limitations stated in the documentation:

请注意文档中声明的XmlMapper限制:

Tree Model is only supported in limited fashion: specifically, Java arrays and Collections can be written, but can not be read, since it is not possible to distinguish Arrays and Objects without additional information.

树模型仅以有限的方式支持:具体而言,Java数组和集合可以编写,但无法读取,因为在没有附加信息的情况下无法区分数组和对象。

Using JSON.org

You also can do it with JSON.org:

您也可以使用JSON.org执行此操作:

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
             "<errors>\n" +
             "  <error>\n" +
             "    <status>400</status>\n" +
             "    <message>The field 'quantity' is invalid.</message>\n" +
             "    <details>\n" +
             "      <invalid_reason>The quantity specified is greater than the quantity of the product that is available to ship.</invalid_reason>\n" +
             "      <available_quantity>0</available_quantity>\n" +
             "      <order_product_id>12525</order_product_id>\n" +
             "    </details>\n" +
             "  </error>\n" +
             "</errors>";

String json = XML.toJSONObject(xml).toString();

The following dependency is required:

需要以下依赖项:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

#2


2  

Is there any way to convert xml to json without using any third party API?

有没有办法在不使用任何第三方API的情况下将xml转换为json?

If you are being practical, no there isn't.

如果你是实际的,没有。

The step of parsing the XML can be performed using APIs that are part of Java SE. However going from the parsed XML (e.g. a DOM) to JSON requires a JSON support library, and Java SE does not include one.

解析XML的步骤可以使用作为Java SE一部分的API来执行。但是,从解析的XML(例如DOM)到JSON需要JSON支持库,而Java SE不包含JSON。

(In theory you could write such a library yourself, but what is the point of doing that?)

(理论上你可以自己编写这样一个库,但这样做有什么意义呢?)


I used Jackson but for this I need to create POJO.

我用过杰克逊,但为此我需要创建POJO。

@Cassio points out that Jackson allows you to do this translation without writing POJOs. Alternatively, look at other (3rd-party) JSON APIs for Java; see http://www.json.org for a list of alternatives. Some of the simpler ones don't involve defining POJOs

@Cassio指出杰克逊允许你在不编写POJO的情况下进行翻译。或者,查看Java的其他(第三方)JSON API;请参阅http://www.json.org以获取备选方案列表。一些较简单的不涉及定义POJO

#3


0  

package com.src.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.io.IOUtils;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

public class JSONConverter {
    private static URL url = null;
    private static InputStream input = null;

    public static void main(String args[]) throws IOException {
        try {
            url = JSONConverter.class.getClassLoader().getResource("sampleXmlFilePath.xml");
            input = url.openStream();
            String xmlData = IOUtils.toString(input);

            XMLSerializer xmlSerializer = new XMLSerializer();
            JSON json = xmlSerializer.read(xmlData);
            System.out.println("JSON format : " + json);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            input.close();
        }
    }
}

#1


12  

Using Jackson 2.x

You can do that with Jackson and no POJOs are required for that:

你可以用Jackson做到这一点,并且不需要POJO:

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
             "<errors>\n" +
             "  <error>\n" +
             "    <status>400</status>\n" +
             "    <message>The field 'quantity' is invalid.</message>\n" +
             "    <details>\n" +
             "      <invalid_reason>The quantity specified is greater than the quantity of the product that is available to ship.</invalid_reason>\n" +
             "      <available_quantity>0</available_quantity>\n" +
             "      <order_product_id>12525</order_product_id>\n" +
             "    </details>\n" +
             "  </error>\n" +
             "</errors>";

XmlMapper xmlMapper = new XmlMapper();
JsonNode node = xmlMapper.readTree(xml.getBytes());

ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node);

The following dependencies are required:

需要以下依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.8.2</version>
</dependency>

Be aware of the XmlMapper limitations stated in the documentation:

请注意文档中声明的XmlMapper限制:

Tree Model is only supported in limited fashion: specifically, Java arrays and Collections can be written, but can not be read, since it is not possible to distinguish Arrays and Objects without additional information.

树模型仅以有限的方式支持:具体而言,Java数组和集合可以编写,但无法读取,因为在没有附加信息的情况下无法区分数组和对象。

Using JSON.org

You also can do it with JSON.org:

您也可以使用JSON.org执行此操作:

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
             "<errors>\n" +
             "  <error>\n" +
             "    <status>400</status>\n" +
             "    <message>The field 'quantity' is invalid.</message>\n" +
             "    <details>\n" +
             "      <invalid_reason>The quantity specified is greater than the quantity of the product that is available to ship.</invalid_reason>\n" +
             "      <available_quantity>0</available_quantity>\n" +
             "      <order_product_id>12525</order_product_id>\n" +
             "    </details>\n" +
             "  </error>\n" +
             "</errors>";

String json = XML.toJSONObject(xml).toString();

The following dependency is required:

需要以下依赖项:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>

#2


2  

Is there any way to convert xml to json without using any third party API?

有没有办法在不使用任何第三方API的情况下将xml转换为json?

If you are being practical, no there isn't.

如果你是实际的,没有。

The step of parsing the XML can be performed using APIs that are part of Java SE. However going from the parsed XML (e.g. a DOM) to JSON requires a JSON support library, and Java SE does not include one.

解析XML的步骤可以使用作为Java SE一部分的API来执行。但是,从解析的XML(例如DOM)到JSON需要JSON支持库,而Java SE不包含JSON。

(In theory you could write such a library yourself, but what is the point of doing that?)

(理论上你可以自己编写这样一个库,但这样做有什么意义呢?)


I used Jackson but for this I need to create POJO.

我用过杰克逊,但为此我需要创建POJO。

@Cassio points out that Jackson allows you to do this translation without writing POJOs. Alternatively, look at other (3rd-party) JSON APIs for Java; see http://www.json.org for a list of alternatives. Some of the simpler ones don't involve defining POJOs

@Cassio指出杰克逊允许你在不编写POJO的情况下进行翻译。或者,查看Java的其他(第三方)JSON API;请参阅http://www.json.org以获取备选方案列表。一些较简单的不涉及定义POJO

#3


0  

package com.src.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.io.IOUtils;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

public class JSONConverter {
    private static URL url = null;
    private static InputStream input = null;

    public static void main(String args[]) throws IOException {
        try {
            url = JSONConverter.class.getClassLoader().getResource("sampleXmlFilePath.xml");
            input = url.openStream();
            String xmlData = IOUtils.toString(input);

            XMLSerializer xmlSerializer = new XMLSerializer();
            JSON json = xmlSerializer.read(xmlData);
            System.out.println("JSON format : " + json);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            input.close();
        }
    }
}