2017-01-06 42 views
2

我想从一个API获取一些Json并解析它们到一些POJO的工作,但我有这种情况下,我可以得到一个简单的字符串或一个数组列表ListList的字符串。杰克逊映射字符串或简单的字符串列表

JSON的是这样的:

{ 
    "offerDisplayCategoryMapping": [ 
    { 
     "offerKey": "EUICC_BASE_ACTIVATION_V01", 
     "categoriesKeys": { 
     "categoryKey": "Included" 
     } 
    }, 
    { 
     "offerKey": "EUICC_BASE_ACTIVATION_V02", 
     "categoriesKeys": { 
     "categoryKey": "Included" 
     } 
    }, 
    { 
     "offerKey": "EUICC_BASE_ACTIVATION_V03", 
     "categoriesKeys": { 
     "categoryKey": [ 
      "Option", 
      "Included" 
     ] 
     } 
    }] 
} 

我使用弹簧安置来从API的结果。我创建了一个代表categoriesKeys的POJO,其中List<String>定义为categoryKey,在我的RestTemplate中定义了ObjectMapper,其中我为DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY启用了简单字符串的情况,但这不起作用!

有什么建议吗?

+0

这将是更容易帮助,如果您添加您的POJO(S)和你的'RestTemplate'在题 –

回答

6

除了已经提到的全局配置,还可以支持这种对各个属性:

public class Container { 
    @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) 
    // ... could also add Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED 
    public List<String> tags; 
} 
2

由于它是一个键列表,它将工作。如果万一酒店有一个值,而不是在阵列像下面 DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY将确保反序列化单一属性的阵列

{ 
    "CategoriesKeys":{ 
    "categoryKey":{ 
     "keys":"1" 
     } 
    } 
} 



@JsonRootName("CategoriesKeys") 
    protected static class CategoriesKeys{ 

     private CategoryKey categoryKey; 
//getters and setters 

} 

protected static class CategoryKey{ 

     private List<String> keys; 
//getters and setters 

} 

TestClass: 

ObjectMapper mapper=new ObjectMapper(); 
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); 
    mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); 
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 

Output: 

{"CategoriesKeys":{"categoryKey":{"keys":["1"]}}} 
3

我曾经使用过春节外杰克逊想这和它的作品如预期有:

ObjectMapper mapper = new ObjectMapper(); 
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); 

介意RestTemplate注册一个MappingJacksonHttpMessageConverter与它自己的ObjectMapperCheck this answer有关如何配置此ObjectMapper

相关问题