首页 > 解决方案 > 将 JSON 映射到包含地图的自定义对象

问题描述

我有一个这样的 json,它嵌套在其中一个字段中 -

{
    "templateid": "email_verified_template",
    "templatevalues": {
        "patient_name": "nprj09”,
        "date": “Monday, 3rd May, 10:37:23 PM”,
    },
    "emailAddress": “nprj09@test.com”,
}

我创建了一个自定义类,

public class EmailTemplate implements Serializable {

    private String templateid;
    private Map<String,String> templatevalues;
    private String emailAddress;

    ---
}

在我的服务类中,我正在读取 json 并将其映射到我的 EmailTemplate 类中,但映射失败。我可以在这里使用什么?

ObjectMapper mapper = new ObjectMapper();
try {
   notificationVo = mapper.readValue(msg, EmailNotificationVO.class);
  

例外:

An Exception has occurred..com.fasterxml.jackson.databind.JsonMappingException: Illegal unquoted character ((CTRL-CHAR, code 13)): has to be escaped using backslash to be included in string value
 at [Source: (String)"{
    "templateid": "email_verified_template",
    "templatevalues": {
        "patient_name": "nprj09”,
        "date": “Monday, 3rd May, 10:37:23 PM”

我尝试添加

mapper.configure(
                    JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(),
                    true
            );

但这也不起作用。

标签: javajsonjacksonobjectmapper

解决方案


映射的代码很好。只需正确输入 JSON。


推荐阅读