【发布时间】:2018-10-25 13:57:12
【问题描述】:
当我反序列化一个对象时,我想对 json 进行一些转换(移动/更改/添加字段),然后继续处理反序列化的对象。这可能吗?
简单示例:
输入 JSON
{
"first": "thing",
"seconds": [ 55, 67, 12 ]
}
我的对象
public class MyObject {
private String new;
private int second;
// getters and setters
}
反序列化器
public class MyObjectDeserializer extends JsonDeserializer<MyObject> {
@Override
public MyObject deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
JsonNode json = p.getCodec().readTree(p);
JsonNode translatedJson = translate(json);
// continue processing MyObject like ObjectMapper#readValue would using the translated json
}
private JsonNode translate(final JsonNode json) {
ObjectNode object = (ObjectNode) json;
// Update 'first' to 'new'
object.put("new", object.get("first").asText()).remove("first");
// Find the max in 'seconds' and add it as 'second'
JsonNode seconds = object.get("seconds");
int max = 0;
for (int i = 0; i < seconds.size(); i++) {
max = Math.max(max, seconds.get(i).asInt());
}
object.put("second", max).remove("seconds");
return object;
}
}
【问题讨论】:
-
你介意举个例子吗?
-
除非您可以更改反序列化器本身的代码,否则您必须将其反序列化为对象,然后使用常规代码将其转换为不同的对象结构。
-
我可以更改反序列化器,但不确定最好的方法,请参见上面的示例。
-
我不知道你需要这个做什么。我认为将其反序列化为接口类,然后映射到您的域实体是更简洁的设计。此外,
new不是有效的类成员名称。