【问题标题】:How to serialize automatically all Annotated fields in JsonSerializer class如何自动序列化 JsonSerializer 类中的所有带注释的字段
【发布时间】:2016-01-26 08:08:51
【问题描述】:

我已经编写了我的 CustomJsonSerializer,我希望它能够自动序列化所有使用 @JsonProperty 注释的字段,所以我只留下序列化那些没有注释且需要“特别注意”的字段。

例如:我有Pojo

类播放器{

@JsonProperty(user_id)
private long userId;

private byte[] history;
}

我的自定义序列化器:

public class JsonPlayerSerializer extends JsonSerializer<Player> {

    @Override
    public void serialize(Player player, JsonGenerator gen,    
         SerializerProvider provider) throws IOException, JsonProcessingException {

          // I would like to add some code here that automatically would add all annotated fields.

          gen.writeObjectField("history_moves", new JsonObject().put("$binary", myMoves));
    }
}

【问题讨论】:

标签: java jackson


【解决方案1】:
   class Player {

     @JsonProperty(user_id)
     private long userId;

     @JsonIgnore
     private byte[] history;
    }

在您的自定义序列化程序中调用父序列化程序方法,以便继续序列化。

public class JsonPlayerSerializer extends JsonSerializer<Player> {

    @Override
    public void serialize(Player player, JsonGenerator gen,    
         SerializerProvider provider) throws IOException, JsonProcessingException {


          super.serialize(player,gen,provider);   
          gen.writeObjectField("history_moves", new JsonObject().put("$binary", myMoves));
    }
}

或者 正如这里提到的 Jackson JSON custom serialization for certain fields

 class Player {

         @JsonProperty(user_id)
         private long userId;

         @JsonSerialize(using = JsonPlayerSerializer .class)
         private byte[] history;
        }

仅对历史字段使用序列化程序

public class JsonPlayerSerializer extends JsonSerializer<Player> {

    @Override
    public void serialize(Player player, JsonGenerator gen,    
         SerializerProvider provider) throws IOException, JsonProcessingException {

          gen.writeObjectField("history_moves", new JsonObject().put("$binary", myMoves));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 2015-07-11
    • 2023-04-02
    • 2018-01-18
    • 1970-01-01
    相关资源
    最近更新 更多