Jackson renames primitive boolean field by removing 'is'

后端 未结 10 807
渐次进展
渐次进展 2020-11-27 12:07

This might be a duplicate. But I cannot find a solution to my Problem.

I have a class

public class MyResponse implements Serializable {

    private          


        
10条回答
  •  渐次进展
    2020-11-27 13:02

    The accepted answer won't work for my case.

    In my case, the class is not owned by me. The problematic class comes from 3rd party dependencies, so I can't just add @JsonProperty annotation in it.

    To solve it, inspired by @burak answer above, I created a custom PropertyNamingStrategy as follow:

    mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
      @Override
      public String nameForSetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName)
      {
        if (method.getParameterCount() == 1 &&
                (method.getRawParameterType(0) == Boolean.class || method.getRawParameterType(0) == boolean.class) &&
                method.getName().startsWith("set")) {
    
          Class containingClass = method.getDeclaringClass();
          String potentialFieldName = "is" + method.getName().substring(3);
    
          try {
            containingClass.getDeclaredField(potentialFieldName);
            return potentialFieldName;
          } catch (NoSuchFieldException e) {
            // do nothing and fall through
          }
        }
    
        return super.nameForSetterMethod(config, method, defaultName);
      }
    
      @Override
      public String nameForGetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName)
      {
        if(method.hasReturnType() && (method.getRawReturnType() == Boolean.class || method.getRawReturnType() == boolean.class)
            && method.getName().startsWith("is")) {
    
          Class containingClass = method.getDeclaringClass();
          String potentialFieldName = method.getName();
    
          try {
            containingClass.getDeclaredField(potentialFieldName);
            return potentialFieldName;
          } catch (NoSuchFieldException e) {
            // do nothing and fall through
          }
        }
        return super.nameForGetterMethod(config, method, defaultName);
      }
    });
    

    Basically what this does is, before serializing and deserializing, it checks in the target/source class which property name is present in the class, whether it is isEnabled or enabled property.

    Based on that, the mapper will serialize and deserialize to the property name that is exist.

提交回复
热议问题