由于objectMapper.writeValueAsString的O / P格式错误,导致无法识别的字段异常

我正在尝试使用Jackson-ObjectMapper将我的hashmap(JSON)反序列化为POJO类。下面是哈希图:

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));
     }
 }

我想使用对象映射器将此请求映射用于我的POJO类,如下所示:

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

我得到以下错误: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:无法识别的字段 “” apptDateTime“”(类Collector.MyRequestDTO)

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

添加Hashmap O / P:

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

输出:关键是“ apptDateTime”值是“ 2019-03-19 10:00:00”关键是    “表”的值为“ 8682”

评论
  • nquis
    nquis 回复

    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.

    您可以通过如下删除包装引号来解决该错误,但是最好修复首先返回意外数据的函数。

        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();
    }