在 springboot 反序列化器中包含带有 jackson 的根对象

Include root object with jackson in springboot deserializer

如何使用 spring-boot 在我的 jackson 解串器中包含 objeto root?

我试着输入 application.properties

spring.jackson.deserialization.UNWRAP_ROOT_VALUE=true

我尝试使用一个配置器

@Configuration
public class JacksonConfig {

    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.featuresToEnable(DeserializationFeature.UNWRAP_ROOT_VALUE);
        builder.indentOutput(true).dateFormat(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"));
        builder.indentOutput(true);
        return builder;
    }

}

然后我在我的课堂上添加了注释

@JsonRootName("contato")
public class TbContato extends EntityBase {

但是没用,我得到了这个 return:

{
  "cdContato": 12,
  "dtContato": "03/08/2015 16:04:43",
  "cdUsuario": null,
  "nmParte": "Fabio Ebner",
  "nmEmailParte": "fabioebner@gmail.com",
  "nmAssunto": "Assuntttoooo",
  "dsMensagem": "mensagem nessa porra aqui",
  "dtResposta": null,
  "dsResposta": null,
  "cdUsuarioResposta": null,
  "nmUsuarioResposta": null
}

没有根。

那是因为你是在序列化而不是反序列化。尝试使用

spring.jackson.serialization.WRAP_ROOT_VALUE=true

另一种选择是像这样参数化泛型 root-wrapper class:

package com.example.wrappedResponse.model;

public class ResponseWrapper<T> {
    private T contato;

    public ResponseWrapper(T contato) {
        this.contato = contato;
    }

    public T getContato() {
        return response;
    }

    public void setContato(T contato) {
        this.contato = contato;
    }
}

然后在控制器中用该类型包装实体。

package com.example.wrappedResponse.controller;

import com.example.wrappedResponse.model.EntityBase;    
import com.example.wrappedResponse.model.ResponseWrapper;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;

@RestController
class EntityWrappingController {

    @GetMapping("/get/wrapped/base/entity")
    public ResponseWrapper<EntityBase> status() {
        EntityBase entityToWrap;
        // get you entity from application …

        return new ResponseWrapper<>(entityToWrap);
    }
}

如果您希望使用同一键进行多个响应换行,这很有意义。