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

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

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

服务器的响应是这样的:

 400The field 'quantity' is invalid.
The quantity specified is greater than the quantity of the product that is available to ship.012525

使用Jackson 2.x

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

 String xml = "\n" + "\n" + " \n" + " 400\n" + " The field 'quantity' is invalid.\n" + " 
\n" + " The quantity specified is greater than the quantity of the product that is available to ship.\n" + " 0\n" + " 12525\n" + "
\n" + "
\n" + "
"; XmlMapper xmlMapper = new XmlMapper(); JsonNode node = xmlMapper.readTree(xml.getBytes()); ObjectMapper jsonMapper = new ObjectMapper(); String json = jsonMapper.writeValueAsString(node);

需要以下依赖项:

  com.fasterxml.jackson.core jackson-core 2.8.2   com.fasterxml.jackson.core jackson-databind 2.8.2   com.fasterxml.jackson.core jackson-annotations 2.8.2   com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.8.2  

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

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

使用JSON.org

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

 String xml = "\n" + "\n" + " \n" + " 400\n" + " The field 'quantity' is invalid.\n" + " 
\n" + " The quantity specified is greater than the quantity of the product that is available to ship.\n" + " 0\n" + " 12525\n" + "
\n" + "
\n" + "
"; String json = XML.toJSONObject(xml).toString();

需要以下依赖项:

  org.json json 20160810  

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

如果你是实际的,没有。

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

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


我用过jackson,但为此我需要创建POJO。

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

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