简体   繁体   English

如何使用Jackson的布尔值的'has'方法命名约定?

[英]How can I use the 'has' method naming convention for booleans with Jackson?

Jackson doesn't handle my boolean fields with a has getter method. 杰克逊不处理我的布尔字段与has getter方法。 For example animal.hasLegs() , for the legs field returns a JSON object without the legs field. 例如, animal.hasLegs() ,对于legs字段,返回没有legs字段的JSON对象。 It does work with the is getter method ( person.isAwesome() for the boolean field awesome ). 它可以使用is getter方法( person.isAwesome()用于布尔字段awesome )。

How can I make Jackson use the has method naming convention for boolean fields? 如何让Jackson使用布尔字段的has方法命名约定?

  1. Annotate all needed hasXXX() methods with @JsonGetter . 注释所有需要的hasXXX()与方法@JsonGetter Otherwise Jackson doesn't use this property at all, because it doesn't start with get : 否则Jackson根本不使用此属性,因为它不以get开头:

     @JsonGetter public boolean hasAwesome() { ... } 
  2. Set custom PropertyNamingStrategy , which renames mapping from method name to JSON field. 设置自定义PropertyNamingStrategy ,它将方法名称的映射重命名为JSON字段。 By default it will generate JSON field named hasXXX . 默认情况下,它将生成名为hasXXX JSON字段。

     ObjectMapper mapper = ... mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() { @Override public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) { String prefix = "has"; if (defaultName.startsWith(prefix)) { String withoutHas = defaultName.replace(prefix, ""); char firstLower = Character.toLowerCase(withoutHas.charAt(0)); return firstLower + withoutHas.substring(1); } return super.nameForGetterMethod(config, method, defaultName); } }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM