java - 忽略 Jackson/spring/Java 中的 RootNode 和自定义映射

标签 java spring jackson deserialization

如果我不需要rootname,我如何忽略它?我只需要账单。

如果我从 json 中删除“版本”,工作正常..

控制台日志上的错误

2019-07-27 19:20:14.874  WARN 12516 --- [p-nio-80-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected token (FIELD_NAME), expected END_OBJECT: Current token not END_OBJECT (to match wrapper object with root name 'bill'), but FIELD_NAME; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (FIELD_NAME), expected END_OBJECT: Current token not END_OBJECT (to match wrapper object with root name 'bill'), but FIELD_NAME
 at [Source: (PushbackInputStream); line: 8, column: 2]]

我的 json 看起来像这样

{
    "bill":
    {
        "siteId":"gkfhuj-00",
        "billId":"d6334954-d1c2-4b51-bb10-11953d9511ea"
        },
    "version":"1"
}

我的 json 类 我尝试使用 JsonIgnoreProperties 但它也没有帮助我写“版本”

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonRootName(value = "bill")
public class Bill {

    private String siteId;
    private String billId;

//getters and setters

我的帖子方法 lisen 对象 Bill

    @PostMapping("/bill")
    @ResponseBody
    public ResponseEntity<String> getBill(@RequestBody Bill bill)

最佳答案

由于您通过注释和 Jackson 依赖 Spring boot,自定义反序列化器将在这里完美工作。您必须创建解串器类,如下所示

public class BillDeserializer extends StdDeserializer<Bill> {

    public BillDeserializer() {
        this(null);
    }

    public BillDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Bill deserialize(JsonParser jp, DeserializationContext ctxt) 
      throws IOException, JsonProcessingException {

        JsonNode billNode = jp.getCodec().readTree(jp);
        Bill bill = new Bill();
        bill.setSiteId(billNode.get("bill").get("siteId").textValue());
        bill.setBillId(billNode.get("bill").get("billId").textValue());      
        return bill;
    }
}

现在您必须指示 Jackson 使用此反序列化器,而不是 Bill 类的默认反序列化器。这是通过注册解串器来完成的。可以通过 Bill 类上的简单注释来完成,例如 @JsonDeserialize(using = BillDeserializer.class)

您的 Bill 类通常如下所示

@JsonDeserialize(using = BillDeserializer.class)
public class Bill {

    private String siteId;
    private String billId;

//getters and setters
}

关于java - 忽略 Jackson/spring/Java 中的 RootNode 和自定义映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57233966/

相关文章:

java - 在 Java 应用程序中处理版本号的好方法是什么?

java - 使用 Tomcat 运行带有外部库的应用程序时出现 NoClassDefFoundError

java - 在 hibernate 中将枚举映射到字符串

java - m2eclipse maven 构建参数

java - JDBC 最大连接数

java - 用于同步请求的 Spring RestTemplate 与 WebClient

java - 使用 Jackson 反序列化递归 Map<String,Object> 后避免类型安全警告

json - Spring 3.2 中 AJAX 的 PUT 方法不起作用

functional-programming - 如何以非阻塞方式解析 Spring 5 WebClient 响应?

java - 将元素添加到 DefaultListModel 时 JList 不更新