0

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"

Mandy
  • 433
  • 2
  • 8
  • 25
  • Please note mapper works fine if json string is formatted like : String content = "{ \"carType\" : \"Mercedes\"}"; – Mandy Apr 08 '20 at 20:49
  • what's contained in `setJSONKeys`? Can you show the code for `apiUtility.readJSONKeys` ? It looks like it's not returning the keys properly. – Joni Apr 08 '20 at 20:50
  • hashmap works correctly see below : 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" – Mandy Apr 08 '20 at 20:52
  • and what does that show you for the key value? – Joni Apr 08 '20 at 20:53
  • Updated response – Mandy Apr 08 '20 at 20:54

1 Answers1

1

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();
}
Joni
  • 108,737
  • 14
  • 143
  • 193