如何告诉jackson将未识别的json数据放入特定字段,同时反序列化

时间:2018-03-26 10:13:18

标签: java json rest jackson-databind

我的数据模型/ 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映射到iDnametitle MyPojo。但是,在使用jackson的ObjectMapper时,我得到一个例外,说globalId未被识别。

这里的问题是它应该将所有这些数据字段(globalIdstatusremarkrelease等)放入属性列表中{{{ 1}})。所以我不应该告诉杰克逊忽略那些。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我认为您需要使用自定义反序列化程序。这样您就可以完全控制如何排列数据

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);