java Jackson 中的 JSON 属性文件不区分大小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30806116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON property file case insensitive in Hymanson
提问by user3124284
I have a JSON property file, which is updated by a user manually.
我有一个 JSON 属性文件,由用户手动更新。
I am mapping it to objects, using Hymanson Object mapper:
我将它映射到对象,使用 Hymanson 对象映射器:
[
{ "id":"01",
"name":"Joe",
"Children" : [ {"Name" : "Alex",
"Age" : "21"},
{"name" : "David",
"Age" : "1"}
]
},
{ "id":"02",
"name":"Hymanson",
"Children" : [ {"Name" : "Mercy",
"Age" : "10"},
{"name" : "Mary",
"Age" : "21"}
]
}
]
Since it is updated manually by a user, they can use any casing; mixed, upper, lower, etc. The solution I have found is, while reading the file I am converting to lower case, like this :
由于它是由用户手动更新的,因此他们可以使用任何大小写;混合、大写、小写等。我找到的解决方案是,在读取文件时,我将转换为小写,如下所示:
String content = new Scanner(new File("filename")).useDelimiter("\Z").next();
After this I am mapping to my object using Hymanson, which works. I am using lower case member names for the mapped classes. Is it the right approach or is there any other way?
在此之后,我使用 Hymanson 映射到我的对象,这很有效。我对映射的类使用小写成员名称。这是正确的方法还是有其他方法?
回答by Kihats
You can use
您可以使用
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
This feature is in Hymanson version 2.5.0 onwards.
此功能在 Hymanson 2.5.0 版以上。
回答by pkozlov
You can use custom PropertyNamingStrategy http://fasterxml.github.io/Hymanson-databind/javadoc/2.1.0/com/fasterxml/Hymanson/databind/PropertyNamingStrategy.html
您可以使用自定义 PropertyNamingStrategy http://fasterxml.github.io/Hymanson-databind/javadoc/2.1.0/com/fasterxml/Hymanson/databind/PropertyNamingStrategy.html
Just create one and configure.
只需创建一个并配置即可。
PropertyNamingStrategy strategy = // ... init
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(strategy);
You can either extend PropertyNamingStrategy class or perhaps it's better to extend PropertyNamingStrategyBase, can be easier.
您可以扩展 PropertyNamingStrategy 类,或者扩展 PropertyNamingStrategyBase 可能更好,可以更容易。