1

I am trying to make a method to which an object is passed and reads all the fields so that the fields that come to null and are String are given the value of "".

The problem now comes with my class. I have this model:

@Getter
@Setter
@NoArgsConstructor
@ToString
public class AccountModel {

    private String noTotCount;
    private int nTotal;
    private String account;

}

And I did this method: private ObjectMapper obMapper = new ObjectMapper();

private Object stringNullToEmpty(Object object) {

    Class<?> clase = object.getClass();
    Map<String, Object> objectMap = obMapper.convertValue(object, new TypeReference<Map<String, Object>>(){});

    for (Field field : clase.getDeclaredFields()) {
        String fieldName = field.getName();
        if(field.getType().equals(String.class) && objectMap.get(fieldName) == null) {
            objectMap.put(field.getName(), "a");

        }
    }

    return obMapper.convertValue(objectMap, clase);

}

The error is presented to me when I make the obMapper.convertValue() because he is converting my noTotCount field to nototCount, so when you go into the conditional and try to put(), there is no field in the objectMap that contains the key noTotCount since the key that contains the objectMap is nototCount.

Why does the ObjectMapper convert my noTotCount field to nototCount?

Nicktar
  • 5,548
  • 1
  • 28
  • 43
jdflores
  • 407
  • 7
  • 25

1 Answers1

1

You have encountered a problem with the java bean naming convention, getter names generated by lombok and jackson when you have camelcase properties with a single letter as the first "word". See this question for further details.

In summary, jackson expects the property (getters and setters) as they would be generated by IDEs (e.g. eclipse): getnTotCount, however I guess that lombok generates getNTotCount (I have not de-lomboked your code). This makes jackson fail (reproduced by renaming the getter).

Workaround: Create the getter yourself and prevent lombok from generating it @JsonProperty("nTotCount") public String getNTotCount() or public String getnTotCount()

sfiss
  • 2,119
  • 13
  • 19