英文:
@JsonDeserialize(builder = ) without annotations
问题
我想反序列化一个在依赖项中定义的不可变类,因此我无法修改它。它只有一个私有构造函数,必须使用构建器来构建。
使用Jackson,可以使用@JsonDeserialize(builder = SomeClass.SomeClassBuilder.class)
来反序列化这样的对象。不幸的是,我无法添加该注解。
是否可以在不使用注解的情况下注册这样的构建器,如果可以的话,您会如何操作?
英文:
I would like to deserialize an immutable class which is defined in a dependency, and therefore I cannot modify. It only has a private constructor, and has to be built using a builder.
With Jackson it's possible to use @JsonDeserialize(builder = SomeClass.SomeClassBuilder.class)
to deserialize such an object. Unfortunately, I cannot add the annotation.
Is it possible to register such a builder without using annotations, and if it is, how would you go about and do it?
答案1
得分: 1
你可以在这里查看示例链接(顺便说一句,这是谷歌搜索的第一个结果):
定义一个自定义的反序列化器:
public class SomeClassDeserializer extends StdDeserializer<SomeClass> {
public SomeClassDeserializer() {
this(null);
}
public SomeClassDeserializer(Class<?> vc) {
super(vc);
}
@Override
public SomeClass deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
// 从节点中读取值并使用 SomeClassBuilder 创建 SomeClass 的实例
}
}
通过向 ObjectMapper
注册反序列化器,使 Jackson 知道该反序列化器的存在:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(SomeClass.class, new SomeClassDeserializer());
mapper.registerModule(module);
SomeClass readValue = mapper.readValue(json, SomeClass.class);
根据您使用的框架,可能还有其他更优雅的方式来注册反序列化器。
英文:
You might want to have a look at the examples here (first hit on google BTW):
Define a custom Deserializer:
public class SomeClassDeserializer extends StdDeserializer<SomeClass> {
public SomeClassDeserializer() {
this(null);
}
public SomeClassDeserializer(Class<?> vc) {
super(vc);
}
@Override
public SomeClass deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
// read values from node and use the SomeClassBuilder
// to create an instance of SomeClass
}
}
Make Jackson aware of the deserializer by registering it with an ObjectMapper
:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(SomeClass.class, new SomeClassDeserializer());
mapper.registerModule(module);
SomeClass readValue = mapper.readValue(json, SomeClass.class);
Depending on the framework you're using there might be other more elegant ways to register the deserializer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论