java - Jackson json反序列化,根元素来自json

标签 java json spring json-deserialization

我向 jackson 提出了一个问题,我认为这个问题应该很容易解决,但它却让我丧命。

我有一个看起来像这样的 java POJO 类(带有 getter 和 setter)

@JsonRootName(value = "notificacion")
public class NotificacionDTO extends AbstractDTO {

@JsonProperty(required=true)
private Integer instalacion;

@JsonProperty(required=true)
private Integer tipoNotificacion;

@JsonProperty(required=true)
private String mensaje;
}

这是 AbstractDTO

public abstract class AbstractDTO implements Serializable {

public void validate() {
    Field[] declaredFields = this.getClass().getDeclaredFields();

    for (Field field : declaredFields) {
        if (field.isAnnotationPresent(JsonProperty.class)){
            if (field.getAnnotation(JsonProperty.class).required() && this.isNullParameter(field)) {
                throw new RuntimeException(String.format("El parametro %s es null o no esta presente en el JSON.", field.getName()));
            }
        }
    }
}

private boolean isNullParameter(Field field) {
    try {
        field.setAccessible(true);
        Object value = field.get(this);

        if (value == null) {
            return true;
        } else if (field.getType().isAssignableFrom(String.class)) {
            return ((String) value).isEmpty();
        }
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return false;
}
}

我想将如下所示的 JSON 反序列化为 NotificacionDTO 对象:

{
  "notificacion":
  {
     "instalacion":"1",
     "tipoNotificacion":"2",
     "mensaje":"Un Mensaje"
  }
}

这是我的端点

@Controller
@RequestMapping("/notificacion")
public class NotificacionEndPoint extends AbstractEndPoint{

@Autowired
private NotificacionService service;

@RequestMapping(value = {"", "/"}, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void addNotification(@RequestBody NotificacionDTO notification) throws JsonParseException, JsonMappingException, IOException {
        this.log.info("[POST RECEIVED] = " + notification);

        notification.validate();

        this.service.addNotification(notification);
}
}

我有一个自定义的 ObjectMapper 与此

public class JsonObjectMapper extends ObjectMapper {

public JsonObjectMapper() {
    super();

    this.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
}
}

当我发布时,我收到此错误

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:  Unrecognized field "notificacion" (class ar.com.tecnoaccion.services.notificacion.NotificacionDTO), not marked as ignorable (3 known properties: , "tipoNotificacion", "instalacion", "mensaje"])
at [Source: org.apache.catalina.connector.CoyoteInputStream@1c1f3f7; line: 3, column:  5] (through reference chain: ar.com.tecnoaccion.services.notificacion.NotificacionDTO["notificacion"])

我尝试将其添加到我的 DTO

 @JsonIgnoreProperties(ignoreUnknown = true)

但是当我使用 validate 所有 dto 的属性都为 null 的方法验证我的 DTO 时,我收到此错误:

 java.lang.RuntimeException: El parametro instalacion es null o no esta presente en el JSON.

我正在使用 jackson 2.2.3 和 spring 3.2.1

谢谢。

最佳答案

简单的答案是发布

{
 "instalacion":"1",
 "tipoNotificacion":"2",
 "mensaje":"Un Mensaje"
}

而不是

{
 "notificacion":
  {
   "instalacion":"1",
   "tipoNotificacion":"2",
   "mensaje":"Un Mensaje"
  }
}

关于java - Jackson json反序列化,根元素来自json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414494/

相关文章:

java - 如何更改工具栏中的菜单图标重力?

java - 注入(inject) Autowiring 的依赖项失败;无法 Autowiring 字段

Spring 启动: Repository interface sql injection protection

javascript - 如何从 JavaScript 输出 JSON 输出,以便将其识别为 JSON?

jquery - 如何通过从多选下拉列表中删除更改时的现有选项来附加新选项?

json - 如何反序列化 WCF Restful 服务的 Json 响应?

java - Jersey & Spring 托管供应商

java - 枚举方法

java - 如何使用java在mongoDB中创建一对多

java - Spring Boot 和 ENUM 导致非法反射访问操作