【问题标题】:Ignore RootNode and custom mapping in Jackson/spring/Java在 Jackson/spring/Java 中忽略 RootNode 和自定义映射
【发布时间】:2019-12-05 14:53:54
【问题描述】:

如果我不需要它,我如何忽略 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

我的post方法lisen对象比尔

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

【问题讨论】:

标签: java spring jackson deserialization


【解决方案1】:

由于您通过注释和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
}

【讨论】:

  • 没有办法只做注释?少了 1 节课
  • 不影响spring默认的杰克逊映射
  • 此实现提供了任何级别的自定义嵌套映射的灵活性
  • 但我可以再开 1 节课,比如 java public class Example { private Bill bill; private String version;
  • 我没有按照您的要求进行操作。添加课程不适合您吗?
猜你喜欢
  • 2014-08-23
  • 2012-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
相关资源
最近更新 更多