忽略杰克逊/春/ Java的根节点和自定义映射

Vaagn Stepanian:

如何,如果我不需要它,我可以忽略根名称?我只需要法案。

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

我的帖子方法丽森对象比尔

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

当你正在依靠Spring boot通过注释和Jackson定制解串器将在这里工作完美无瑕。你必须创建解串器类,如下所示

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类。这是由注册desearilizer完成。它可以通过一个简单的注解在做Bill类似的类@JsonDeserialize(using = BillDeserializer.class)

你的Bill类通常看起来如下规定

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

    private String siteId;
    private String billId;

//getters and setters
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章