Jackson renames primitive boolean field by removing 'is'

后端 未结 10 845
渐次进展
渐次进展 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 12:42

    there is another method for this problem.

    just define a new sub-class extends PropertyNamingStrategy and pass it to ObjectMapper instance.

    here is a code snippet may be help more:

    mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
            @Override
            public String nameForGetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName) {
                String input = defaultName;
                if(method.getName().startsWith("is")){
                    input = method.getName();
                }
    
                //copy from LowerCaseWithUnderscoresStrategy
                if (input == null) return input; // garbage in, garbage out
                int length = input.length();
                StringBuilder result = new StringBuilder(length * 2);
                int resultLength = 0;
                boolean wasPrevTranslated = false;
                for (int i = 0; i < length; i++)
                {
                    char c = input.charAt(i);
                    if (i > 0 || c != '_') // skip first starting underscore
                    {
                        if (Character.isUpperCase(c))
                        {
                            if (!wasPrevTranslated && resultLength > 0 && result.charAt(resultLength - 1) != '_')
                            {
                                result.append('_');
                                resultLength++;
                            }
                            c = Character.toLowerCase(c);
                            wasPrevTranslated = true;
                        }
                        else
                        {
                            wasPrevTranslated = false;
                        }
                        result.append(c);
                        resultLength++;
                    }
                }
                return resultLength > 0 ? result.toString() : input;
            }
        });
    

提交回复
热议问题