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

如果我不需要它,我怎么能忽略它?我只需要账单。


如果我从 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 对象 Bill


    @PostMapping("/bill")

    @ResponseBody

    public ResponseEntity<String> getBill(@RequestBody Bill bill)


胡子哥哥
浏览 101回答 1
1回答

守候你守候我

由于您依赖于Spring bootthrough 注释和Jackson,因此自定义反序列化器将在这里完美运行。您必须创建反序列化器类,如下所示public class BillDeserializer extends StdDeserializer<Bill> {&nbsp; &nbsp; public BillDeserializer() {&nbsp; &nbsp; &nbsp; &nbsp; this(null);&nbsp; &nbsp; }&nbsp; &nbsp; public BillDeserializer(Class<?> vc) {&nbsp; &nbsp; &nbsp; &nbsp; super(vc);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public Bill deserialize(JsonParser jp, DeserializationContext ctxt)&nbsp;&nbsp; &nbsp; &nbsp; throws IOException, JsonProcessingException {&nbsp; &nbsp; &nbsp; &nbsp; JsonNode billNode = jp.getCodec().readTree(jp);&nbsp; &nbsp; &nbsp; &nbsp; Bill bill = new Bill();&nbsp; &nbsp; &nbsp; &nbsp; bill.setSiteId(billNode.get("bill").get("siteId").textValue());&nbsp; &nbsp; &nbsp; &nbsp; bill.setBillId(billNode.get("bill").get("billId").textValue());&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return bill;&nbsp; &nbsp; }}现在你必须指示你Jackson使用这个反序列化器而不是类的默认反序列化器Bill。这是通过注册 desearilizer 来完成的。可以通过Bill类上的简单注释来完成,例如@JsonDeserialize(using = BillDeserializer.class)您的Bill课程通常如下所示@JsonDeserialize(using = BillDeserializer.class)public class Bill {&nbsp; &nbsp; private String siteId;&nbsp; &nbsp; private String billId;//getters and setters}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java