我从服务器收到 XML 格式的响应。但我需要以 JSON 格式显示它。
没有任何第三方API,有什么方法可以转换它吗?我使用了 Jackson,但为此我需要创建 POJO。
服务器的响应是这样的:
<?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>
最佳答案
使用 jackson 2.x
您可以使用 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);
需要以下依赖项:
<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>
请注意 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.
Jackson author in the comments 很好地强调了这一点, Jackson 2.12 终于 improved XML handling ,以便 if 使用 JsonNode
或 Object
作为目标类型保留重复项。
使用 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();
需要以下依赖:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
关于java - 如何仅使用 Jackson 将 XML 转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39493173/