我在Sping Boot 应用程序中有这样的@RestController:
package test.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping("/test")
public class TestController {
public static class Person {
public String fullName;
public Person(String fullName) {
this.fullName = fullName;
}
}
@GetMapping(value = "", produces = {"application/json", "application/xml"})
public List<Person> getPeople() {
return Arrays.asList(new Person("Name1"), new Person("Name2"));
}
}
它返回这样的XML:
<List>
<item>
<FullName>Name1</FullName>
</item>
<item>
<FullName>Name2</FullName>
</item>
</List>
比如JSON:
[{"FullName":"Name1"},{"FullName":"Name2"}]
这个结构几乎适合我。
SpringDoc生成这样openapi代码:
{
"/test" : {
"get" : {
"tags" : [
"test-controller"
],
"operationId" : "getPeople",
"responses" : {
"200" : {
"description" : "OK",
"content" : {
"application/json" : {
"schema" : {
"type" : "array",
"items" : {
"$ref" : "#/components/schemas/Person"
}
}
},
"application/xml" : {
"schema" : {
"type" : "array",
"items" : {
"$ref" : "#/components/schemas/Person"
}
}
}
}
}
}
}
},
"components" : {
"schemas" : {
"Person" : {
"type" : "object",
"properties" : {
"fullName" : {
"type" : "string"
}
},
"description" : ""
}
}
}
}
- JSON没有问题,但是对于XML格式,没有提到 List/item 标记,并且swagger-ui for XML example中出现错误“XML example cannot be generated;根元素名称未定义”。如果REST方法必须返回一个列表,并且需要openapi文档,那么应该怎么做?
1.如何更改 List 和 item XML标签的名称?
我尝试扩展ArrayList,使List成为我的类的字段,使用各种注解,但没有达到预期的效果(取决于保存所需的响应结构)。
1条答案
按热度按时间lztngnrs1#
经过多次测试后,我最近的解决方案-添加 Package 器类和一些注解:
JSON结构发生了变化:该列表现在在字段
Persons
中。