ジャクソン/春/ 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のための私のクラスiの利用JsonIgnorePropertiesが、そのいけないの助けも私の書き込み、「バージョン」を試します

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

    private String siteId;
    private String billId;

//getters and setters

対象ビルlisen私の投稿方法

    @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
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=239904&siteId=1