如何在REST响应中解析jsonObject和JsonArray为同一字段

时间:2018-07-13 07:18:56

标签: json rest deserialization resttemplate

我已经使用RestTemplate调用了一个api,让我们假设/ getCompany

通常的响应如下:-

"Organization":{
  "name": "My Company",
  "department": {
     "id": "1",
     "employee": [{
       "id": "84",
       "name": "abc"
      },
      {
       "id": "85",
       "name": "xyz"
      }]
 }
}

所以我要解析如下:-

ResponseEntity<Organization> company= new RestTemplate().exchange(new URI(companyUrl),HttpMethod.GET,request, Organization.class);
Organization comp= company.getBody();
Department dept= comp.getDepartment();
Employee[] emp = dept.getEmployees()

但是有时在响应中,我还会得到以下json字符串:

"Organization":{
  "name": "My Company",
  "department": {
     "id": "1",
     "employee": {
       "id": "84",
       "name": "abc"
      }     
   }
}

现在我得到以下异常:-

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of Employee[] out of START_OBJECT token

那么有什么办法可以处理这两种情况?

更新:-

根据评论添加以下代码:-

@Bean
public ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    return objectMapper;
}

@Bean
public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter(ObjectMapper objectMapper) {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(objectMapper);
    return converter;
}

但仍然出现相同的异常。

谢谢

2 个答案:

答案 0 :(得分:3)

已注册的objectMapper必须与ACCEPT_SINGLE_VALUE_AS_ARRAY参数一起使用。

达到此目的的最简单方法是在带有ObjectMapper注释的类中注册正确初始化的MappingJacksonHttpMessageConverter@Configuration

@Bean
public ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(ACCEPT_SINGLE_VALUE_AS_ARRAY);
    return objectMapper;
}

@Bean
public MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter(ObjectMapper objectMapper) {
    MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
    converter.setObjectMapper(objectMapper);
    return converter;
}

另一种方法是将转换器直接设置为restTemplate对象:

public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(ACCEPT_SINGLE_VALUE_AS_ARRAY);
    return objectMapper;
}


public MappingJackson2HttpMessageConverter httpConverter(ObjectMapper objectMapper) {
    return new MappingJackson2HttpMessageConverter(objectMapper);
}

public void restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(Arrays.asList(httpConverter(objectMapper())));
    restTemplate.exchange(...);
}

答案 1 :(得分:-3)

JSON是一种javascript对象表示法。 JSON与javascript的语法相同。在JSON中,数组值的类型必须为字符串,数组,数字,对象布尔值或null。