簡體   English   中英

如何告訴傑克遜在反序列化時將無法識別的json數據放入特定字段

[英]how to tell jackson to put unrecognized json data into a particular field while deserializing

我的數據模型/ POJO:

public class MyPojo {

    @JsonProperty("description")
    protected String content;

    @JsonProperty("name")
    protected String title;

    @JsonProperty("property")
    protected List<Property> property;

    @JsonProperty("documentKey")
    protected String iD;

    // Getters and setters...

}

但是,我的服務器以以下格式返回json響應。

{
  "documentKey": "J2D2-SHRQ1_2-55",
  "globalId": "GID-752726",
  "name": "SHReq - Textual - heading test",
  "description": "some text",
  "status": 292,
  "rationale$58": "Value of rationale",
  "remark": "Just for testing purposes",
  "release": 203
}

在這里,我已將documentKey映射到iD並將name映射到MyPojo title 但是,在使用傑克遜的ObjectMapper ,出現了一個異常,指出globalId沒有被確認。

這里的問題是它應該將所有這些數據字段( globalIdstatusremarkrelease等)放入屬性List<Property> propertyList<Property> property )中。 所以我不應該告訴傑克遜忽略這些。

我怎樣才能做到這一點?

我認為您將需要使用自定義反序列化器。 這樣,您可以完全控制如何安排數據

class MyPojoDeserializer extends StdDeserializer<MyPojo> {

  public MyPojoDeserializer() {
    this(null);
  }

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

  @Override
  public MyPojo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonNode node = jp.getCodec().readTree(jp);

    MyPojo myPojo = new MyPojo();

    myPojo.setId(node.get("documentKey").asText());
    myPojo.setContent(node.get("documentKey").asText());
    myPojo.setTitle(node.get("name").asText());

    // I just make a list of Strings here but simply change it to make a List<Property>, 
    // I do not know which Property class you want to use
    List<String> properties = new ArrayList<>();
    properties.add(node.get("globalId").asText());
    properties.add(node.get("status").asText());
    properties.add(node.get("rationale$58").asText());
    properties.add(node.get("remark").asText());
    properties.add(node.get("release").asText());
    myPojo.setProperty(properties);

    return myPojo;
  }
}

然后將以下注釋添加到MyPojo類中

@JsonDeserialize(using = MyPojoDeserializer.class)
public class MyPojo {
  protected String id;
  protected String content;
  protected String title;
  protected List<Property> property;

  // Getters/Setters

}

然后經典的readValue調用應該可以工作

MyPojo myPojo = new ObjectMapper().readValue(json, MyPojo.class);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM