英文:
Generic POJO to JSON using jackson with dynamic json key as per Generic class
问题
我有一个类似的POJO:
class Wrapper<T> {
private int count;
private T data;
// 获取器和设置器
}
当使用Jackson将其转换为JSON时,JSON大致如下:
{
count:1,
**data**:{}
}
我需要根据类名T或与类名相关的其他值来更改data键,我应该如何实现这一点。请给予建议。谢谢。
英文:
I have a POJO like:
class Wrapper,T> {
private int count;
private T data;
// getters setters
}
While converting it to JSON using Jackson, json is something like:
{
count:1,
**data**:{}
}
I need the data key to be changed as per class name T or some other value related to class name, how can I achieve this. Please suggest.
Thankyou.
答案1
得分: 1
使用自定义序列化器,您可以做任何您想要的事情,因为您对序列化过程拥有完全控制权。例如,请参阅https://www.baeldung.com/jackson-custom-serialization。
您的serialize
方法可能如下所示:
@Override
public void serialize(
Wrapper<?> value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String derivedName = value.getClass().getSimpleName() + "Data"; // 仅为示例
jgen.writeStartObject();
jgen.writeNumberField("count", value.getCount());
jgen.writeObjectField(derivedName, value.getData());
jgen.writeEndObject();
}
英文:
Using a custom serializer, you can do anything you want since you have complete control over the serialization process. See for example https://www.baeldung.com/jackson-custom-serialization.
Your serialize
method would look something like this:
@Override
public void serialize(
Wrapper<?> value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String derivedName = value.getClass().getSimpleName() + "Data"; // just an example
jgen.writeStartObject();
jgen.writeNumberField("count", value.getCount());
jgen.writeObjectField(derivedName, value.getData());
jgen.writeEndObject();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论