首页 > 解决方案 > 获取 @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可以有一个Units 列表,这是一个未交换的<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测试的任何想法?

标签: javaspring-bootjackson-dataformat-xml

解决方案


推荐阅读