java - 获取 @RestController 中使用的 ObjectMapper
问题描述
我有一个 Spring Boot @RestController
,它有一个上传 endpiont,它获取一个对象作为输入。
public ResponseEntity<Void> upload(String productId, Boolean dryrun, ProductConfig product)
此端点接收一个包含 a 的 xml 文件ProductConfig
。我有一些 Jackson 注释,用于重命名 xml 元素和配置以在默认情况下使用未包装列表,Jackson2ObjectMapperBuilder
并且工作正常。
所以我的问题是现在我需要ObjectMapper
在我的一项测试中使用它来解析资源中的这些 xml 文件之一。我尝试了两种不同的方法:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TestIntegrationTest {
@Autowired ObjectMapper mapper;
@Test
public void test() throws Exception{
Resource res = new ClassPathResource("SimpleConfig.xml");
ProductConfig conf = mapper.readValue(res.getFile(), ProductConfig.class);
}
}
和
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TestIntegrationTest {
@Test
public void test() throws Exception{
XmlMapper mapper = new XmlMapper();
mapper.setDefaultUseWrapper(false);
Resource res = new ClassPathResource("SimpleConfig.xml");
ProductConfig conf = mapper.readValue(res.getFile(), ProductConfig.class);
}
}
第一个是我希望工作的那个,但它在“<”字符上出现解析异常而崩溃,这似乎是它想要解析 json 而不是 xml,但@RestController
它被完美解析,......或是 ObjectMapper 不是解析的类@RestController
吗?
在第二个示例中,它无法解析一些嵌套类,即ProductConfig
可以有一个Unit
s 列表,这是一个未交换的<unit>
子元素列表。模型的相应部分是:
@JsonProperty("units")
@JacksonXmlProperty(localName = "unit")
@Valid
private List<Unit> units = null;
XmlMapper
这在我只是将 xml 上传到其余端点时有效,但在我手动调用时不起作用。
xml 看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<product name="foobar">
<unit target="config">
<property name="prop1" value="foo"/>
<unit target="sub1">
<property name="prop1" value="foo"/>
<property name="prop2" value="bar"/>
<property name="prop3" value="blah"/>
</unit>
<unit target="sub2">
....
</unit>
...
</unit>
</product>
关于如何重现解析@RestController
测试的任何想法?
解决方案
推荐阅读
- python - 如何从 tkinter 中的绑定回调中获取回调引用?
- python - 为什么这个简单的重新索引 Panda df 函数不起作用?
- node.js - 如何将消息从用 Node.js 编写的本机应用程序发送到 Chrome 扩展程序?
- javascript - 如何在反应中从不同的驱动器导入组件?
- c - 对数组内的字符串内容进行排序
- html - 响应式 HTML 表格中缺少右填充
- mainframe - JCL 打印作业假脱机到特定 LPAR 的数据集中
- python - 如何在python中使用变量作为属性
- reactjs - 如何在打字稿/反应中创建一个基本的观察者类?
- c++ - 用数据填充未指定大小的数组