spring-boot jackson单个对象作为数组

时间:2016-02-20 21:58:50

标签: java spring-boot

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

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

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

@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

Ps:如果我在没有休息模板的情况下尝试此操作,它会按预期工作

@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>();

此致

1 个答案:

答案 0 :(得分:2)

当你这样做时

restTemplate.getMessageConverters().add(converter);

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

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

如果您将该段代码更改为

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

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