弹簧启动杰克逊单个对象作为数组

亚当

我在将单个对象解析为数组时遇到问题,我使用了以下属性

# JACKSON (JacksonProperties).
spring.jackson.deserialization.ACCEPT_SINGLE_VALUE_AS_ARRAY=true

除上述内容外,我还配置了一个rest模板,如下所示:

@Test
    public void testSingleObject() {
        RestTemplate restTemplate = new RestTemplate();
         ObjectMapper mapper = new ObjectMapper();
        MappingJackson2HttpMessageConverter convertor = new MappingJackson2HttpMessageConverter();
        convertor.setObjectMapper(mapper);
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        restTemplate.getMessageConverters().add(convertor);
        MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
        mockServer.expect(requestTo("/test/1")).andExpect(method(HttpMethod.GET))
                .andRespond(withSuccess("{\"size\":\"1\",\"Value\":{\"@id\": \"1\",\"description\":\"Some Text\"}}", MediaType.APPLICATION_JSON));
       // JsonNode jsonNode = restTemplate.getForObject("/test/{id}", JsonNode.class, 1);
        mycalss value = restTemplate.getForObject("/test/{id}", myclass.class, 1);
        System.out.print(value.toString());
    }

我正在使用spring-boot 1.3.2,我得到的错误是

Could not read document: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

附言:如果我在没有休息模板的情况下尝试此方法,则可以正常工作

@Test
    public void testSingleObject3() throws IOException {
        final String json = "{\"size\":\"1\",\"Value\":{\"@id\": \"1\",\"description\":\"Some Text\"}}";

        final ObjectMapper mapper = new ObjectMapper()
                .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        myclass value = mapper.readValue(json,
                new TypeReference<myclass>() {
        });
        System.out.println(value.toString());
    }

我的课定义如下:

//@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class myclass {
@JsonProperty("size")
private String Size;
@JsonProperty("value")
private List<mysubclass> mysubclass;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>(); 
//... setters and getters 

mysubclass的定义如下:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"id",
"description"
})
public class mysubclass {

@JsonProperty("@id")
private String Id;
@JsonProperty("description")
private String description;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

问候

mzc

当你做

restTemplate.getMessageConverters().add(converter);

您实际上是在转换器RestTemplate列表中添加了第二个杰克逊转换器。

运行代码时,将使用第一个代码(由RestTemplate构造函数默认添加),因此配置第二个代码无关紧要。

如果您将这段代码更改为

restTemplate.setMessageConverters(Collections.singletonList(converter));

默认转换器将被丢弃,仅使用您配置的转换器。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章