我有一个像这样的POJO:
public class Person {
public long id;
public String someOtherId;
public String vollName;
public int alter;
}
我正在使用 mixin 将 POJO 转换为 JSON:
@JsonIncludeProperties( { "id", "name", "age", "customFields" } )
abstract class PersonM extends Person {
@JsonProperty( "id" ) String someOtherId;
@JsonProperty( "name" ) String vollName;
@JsonProperty( "age" ) String alter;
}
...
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn( Person.class, PersonM.class );
String body = mapper.writeValueAsString( person );
代码的工作原理就像魅力一样,并生成以下 JSON:
{
"id": "xxxxxx",
"name": "Aaaa Bbbb",
"age": 111
}
现在我需要扩展 JSON 以包含
customFields
元素:
{
"id": "xxxxxx",
"name": "Aaaa Bbbb",
"age": 111,
"customFields": {
"originalId": 333333
}
}
这样新元素的内容基于同一 POJO 的其他字段,并且看起来像 getter:
public class Person {
...
public Map getCustomFields() { return Map.of( "originalId", id ); }
}
由于多种原因,我不想将这个或类似的方法包含到我的 POJO 中,并且希望在
StdDeserializer<>
级别上进行。
在互联网上我找不到任何向现有字段添加另一个 JSON 元素的示例,所有示例都显示从头开始构建 JSON。
因此问题是:如何将 JSON 对象添加到现有输出中,而无需一遍又一遍地“重新发明轮子”?
通过扩展 JsonDeserializer 创建自定义 PersonDeserializer。在 deserialize 方法中,我们从 JSON 节点中提取 id、name 和age 值。然后,我们创建一个 Person 对象并相应地设置其属性。此外,我们创建一个 customFields 映射并用所需的自定义字段值填充它。最后,我们在 Person 对象上设置 customFields 映射。
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class PersonDeserializer extends JsonDeserializer<Person> {
@Override
public Person deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectNode node = jsonParser.getCodec().readTree(jsonParser);
long id = node.get("id").asLong();
String name = node.get("name").asText();
int age = node.get("age").asInt();
Person person = new Person();
person.setId(id);
person.setName(name);
person.setAge(age);
Map<String, Object> customFields = new HashMap<>();
customFields.put("originalId", id);
person.setCustomFields(customFields);
return person;
}
}
要使用此自定义反序列化器,您需要将其注册到 ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Person.class, new PersonDeserializer());
mapper.registerModule(module);
String json = mapper.writeValueAsString(person);