如何告诉杰克逊在反序列化时将无法识别的 JSON 数据放入特定字段



My data model/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映射到iDname映射到MyPojotitle。然而,在使用杰克逊的ObjectMapper时,我得到一个例外,说globalId没有被识别。

这里的问题是它应该把所有这样的数据字段(globalIdstatusremarkrelease等)放到属性列表中(List<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
}

然后经典的读取值调用应该可以工作

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

最新更新