我在将单个对象解析为数组时遇到问题我使用了以下属性
# 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());
}
我的类(class)定义如下:
//@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>();
问候
最佳答案
当你做
restTemplate.getMessageConverters().add(converter);
您实际上是在
RestTemplate
的转换器列表中添加了第二个 jackson 转换器。当您运行代码时,正在使用第一个(由
RestTemplate
构造函数默认添加),因此您是否配置了第二个并不重要。如果你把那段代码改成
restTemplate.setMessageConverters(Collections.singletonList(converter));
默认转换器将被丢弃,只会使用您配置的转换器。
关于java - spring-boot jackson 单个对象作为数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35529581/