【问题标题】:Jackson Mapping List of String or simple String字符串或简单字符串的杰克逊映射列表
【发布时间】:2017-05-21 03:11:57
【问题描述】:

我正在尝试从 API 获取一些 Json 并将它们解析为一些 POJO 以使用它们,但我有这种情况,我可以获取一个简单的字符串或字符串数​​组列表作为键。

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"
        ]
      }
    }]
}

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

有什么建议吗?

【问题讨论】:

  • 如果您在问题中添加您的 pojo(s) 和 RestTemplate,会更容易提供帮助

标签: java json spring jackson mapper


【解决方案1】:

因为它是一个键列表,所以它可以工作。如果万一属性具有单个值而不是像下面这样的数组 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"]}}}

【讨论】:

    【解决方案2】:

    我已经在 Spring 之外的 jackson 上尝试过这个,它可以按预期工作:

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

    注意RestTemplate 用它自己的ObjectMapper 注册了一个MappingJacksonHttpMessageConverterCheck this answer 了解如何配置此ObjectMapper

    【讨论】:

      【解决方案3】:

      除了已经提到的全局配置之外,还可以在单​​个属性上支持这一点:

      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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        相关资源
        最近更新 更多