Search code examples
gsonjson-deserializationspring-boot-configuration

GSON deserializing null value not working


I am trying to de-serialize the json string. I tried different API's but I didn't find the solution. Here, am trying to deserialize below json and want to read value of each field/element. Example below -

 String inputJson = "{"phone":null, "address":"underworld"}";
 LinkedTreeMap map = new Gson().fromJson(inputJson , LinkedTreeMap.class);

When I say map.containsKey("phone), it is giving as false, it means "phone" element is not present in the json string. But, this is not correct as we could see that this element is present in the input json.

Can anyone help me on any API which can give keys with value as well.

With spring boot what is the correct jackson deserialization configuration which can accept null values? Currently I am using like below -

pubic ObjectMapper objectMapper(Jckson3OjectMapperBuilder builder) {
      ObjectMapper  mapper = builder.build();
      mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      return mapper;
   }

Solution

  • I have solved this problem by changing spring boot end point method argument signature from Object to String. Earlier it was Object type because of that it just ignoring keys having null values in the String. And in the controller I am checking the existence of the key as below -

    public ResponseEntity<Object> validate(@RequestBody String requestBody) {
    Object requestObject = new ObjectMapper().readValue(requestBody, Object.class);
    LinkedTreeMap requestObjectMap = new Gson().fromJson(requestObject.toString(), LinkedTreeMap.class);
    List<FieldError> fieldErrors = new ArrayList<>();
    final boolean isKeyExists = requestObjectMap.containsKey("keyname");
    final Object fieldValue = requestObjectMap.get(optionalField);
    if (isKeyExists && (Objects.isNull(fieldValue)) {
      System.out.println("Key exists but its value is null in the input Json request");
    }
    
    // other logic
    

    }