我有一个使用 SpringBoot 编写的 Controller 操作,用于处理/greeting 的 POST 请求并返回字符串响应。我的目的是将 json 有效负载转换为 xml,并最终使用 xml 有效负载命中另一个 Web 服务。我尝试了以下方法将 json 转换为 xml。然而 xml 转换永远不会发生。我收到 JSON 响应。
GreetingController.java
@RequestMapping(value = "/greeting", method = RequestMethod.POST, consumes = "application/json")
public String greeting(@RequestBody final Greeting greeting) throws JsonProcessingException
{
final ObjectMapper xmlMapper = new ObjectMapper();
final String xml = xmlMapper.writeValueAsString(greeting);
return xml;
}
Greeting.java
package com.fmr.communication.delivery.stream.model;
import com.fasterxml.jackson.databind.JsonNode;
public class Greeting
{
private long id;
private String content;
private JsonNode parent;
public String getContent()
{
return content;
}
public long getId()
{
return id;
}
public JsonNode getParent()
{
return parent;
}
public void setContent(final String content)
{
this.content = content;
}
public void setId(final long id)
{
this.id = id;
}
public void setParent(final JsonNode parent)
{
this.parent = parent;
}
}
请求(也是我收到的响应)
{
"id":2,
"content":"Hello, User!",
"parent":{
"child":{
"header":{
"attrOne":"value1",
"attrTwo":"value2"
},
"footer":{
"attrOne":"value1",
"attrTwo":"value2"
}
}
}
}
预期响应
<?xml version="1.0" encoding="UTF-8"?>
<root>
<content>Hello, User!</content>
<id>2</id>
<parent>
<child>
<footer>
<attrOne>value1</attrOne>
<attrTwo>value2</attrTwo>
</footer>
<header>
<attrOne>value1</attrOne>
<attrTwo>value2</attrTwo>
</header>
</child>
</parent>
</root>
最佳答案
只需在您的 pom 中添加此依赖项,并将“Accept” header 作为“application/xml”传递,它就会动态地将 JSON 转换为 xml。
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
关于java - 使用 Spring Boot 将 JSON 负载转换为 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43528254/