使用Jackson将通用POJO转换为JSON,根据通用类动态生成JSON键。

huangapple go评论114阅读模式
英文:

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&gt; {
     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&lt;?&gt; value, JsonGenerator jgen, SerializerProvider provider) 
  throws IOException, JsonProcessingException {

    String derivedName = value.getClass().getSimpleName() + &quot;Data&quot;; // just an example

    jgen.writeStartObject();
    jgen.writeNumberField(&quot;count&quot;, value.getCount());
    jgen.writeObjectField(derivedName, value.getData());
    jgen.writeEndObject();
}

huangapple
  • 本文由 发表于 2020年3月16日 17:23:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/60703286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定