Search code examples
javajsonjacksonjsonschema2pojo

Unrecognized field exception due to Incorrectly formatted O/P of objectMapper.writeValueAsString


I am trying to deserialize my hashmap(JSON) to POJO class using Jackson - ObjectMapper . Below is the hashmap :

List<Object> setJSONValues = new ArrayList<Object>(Arrays.asList(requestObj));
List<String> setJSONKeys = apiUtility.readJSONKeys(new  File("ABC.csv"));
HashMap<String, Object> requestMap = new HashMap<String, Object>();
 if (setJSONKeys.size() == setJSONValues.size()) {
     for (int i = 0; i < setJSONKeys.size(); i++) {
                requestMap.put(setJSONKeys.get(i), setJSONValues.get(i));
     }
 }

I want to use this requestMap into my POJO class using object mapper see below :

objectMapper.readValue(objectMapper.writeValueAsString(requestMap), MyRequestDTO.class);

I get below error : com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field " "apptDateTime"" (class Collector.MyRequestDTO)

Above error is coming because O/P of my objectMapper.writeValueAsString(requestMap) is : {" \"apptDateTime\"":"\"2019-03-19 10:00:00\"","\"meter\"":"\"8682\""

Adding Hashmap O/P :

for (String s:requestMap.keySet())
  System.out.println("Key is "+s+"Value is "+requestMap.get(s));

Output : Key is "apptDateTime"Value is "2019-03-19 10:00:00" Key is "meter"Value is "8682"


Solution

  • Your utility method for reading the keys does not work as you expect (this one:)

    List<String> setJSONKeys = apiUtility.readJSONKeys(new  File("ABC.csv"));
    

    It is returning keys and values wrapped in double quotes, so a key that is supposed to be "apptDateTime" is actually returned as " \"apptDateTime\"". You can see this in the debug output you added: you don't add quotes around the keys or the values, but the output shows quotes anyway.

    You can work around the bug by removing the wrapping quotes as follows, but it would be better to fix the function that returns unexpected data in the first place.

        String key = removeQuotes(setJSONKeys.get(i));
        String value = removeQuotes(setJSONValues.get(i))
        requestMap.put(key, setJSONValues.get(i));
    
    ...
    
    String removeQuotes(String key) {
        key = key.trim();
        key = key.substring(1, key.length() - 1); // remove quotes
        return key.trim();
    }