JSON 属性 Jackson 文件不区分大小写

JSON property file case insensitive in Jackson

我有一个 JSON 属性 文件,由用户手动更新。

我正在使用 Jackson 对象映射器将其映射到对象:

[ 
   {  "id":"01",
      "name":"Joe",
      "Children" : [ {"Name" : "Alex",
                       "Age" : "21"},
                     {"name" : "David",
                      "Age" : "1"}
                   ]
    },
    {  "id":"02",
       "name":"Jackson",
       "Children" : [ {"Name" : "Mercy",
                       "Age" : "10"},
                      {"name" : "Mary",
                       "Age" : "21"}
                    ]
    }
]

由于是用户手动更新,所以可以使用任何大小写;混合,大写,小写等。我找到的解决方案是,在读取我正在转换为小写的文件时,如下所示:

 String content = new Scanner(new File("filename")).useDelimiter("\Z").next();

在此之后,我使用 Jackson 映射到我的对象,这很有效。我为映射 类 使用小写成员名称。这是正确的方法还是有其他方法?

您可以使用自定义 PropertyNamingStrategy http://fasterxml.github.io/jackson-databind/javadoc/2.1.0/com/fasterxml/jackson/databind/PropertyNamingStrategy.html

只需创建一个并配置即可。

PropertyNamingStrategy strategy = // ... init
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(strategy);

您可以扩展 PropertyNamingStrategy class 或者最好扩展 PropertyNamingStrategyBase,这样会更容易。

您可以使用

ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

此功能在 Jackson 2.5.0 及更高版本中。