我正在尝试以XML响应的形式返回调查列表。我能够得到以下回应:
<List>
<item>
<title>My Favorite Survey</title>
<description>Description of the Survey</description>
<surveyId>Survey1</surveyId>
<questions>
<question>...</question>
<question>...</question>
</questions>
</item>
</List>
但是,我想显示如下响应:
<surveys>
<survey>
<title>My Favorite Survey</title>
<description>Description of the Survey</description>
<surveyId>Survey1</surveyId>
<questions>
<question>...</question>
<question>...</question>
</questions>
</survey>
</surveys>
这是我的POJO课程:
@JacksonXmlRootElement(localName="survey")
public class Survey {
@JacksonXmlProperty(localName = "surveyId")
private String id;
private String title;
private String description;
@JacksonXmlElementWrapper(localName = "questions")
@JacksonXmlProperty(localName = "question")
private List<Question> questions;
// getters and setters
}
控制器类:
@RestController
class SurveyController {
@Autowired
private SurveyService surveyService;
@GetMapping(path = "/surveys")
public List<Survey> retrieveQuestions() {
return surveyService.retrieveAllSurveys();
}
}
好像@JacksonXmlRootElement(localName="survey")
在我的情况下不起作用,我可以做什么列表显示为调查。请指导我如何使用我的自定义标签名称代替列表和项目。
对于XML内容,我建议编写一个XSD,然后使用以下Maven插件生成JAXB类:
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<generatePackage>com.mycompany.myproject.jaxb</generatePackage>
</configuration>
</execution>
</executions>
<configuration>
<args>
<arg>-mark-generated</arg>
</args>
<locale>en</locale>
</configuration>
</plugin>