如何自动序列化JsonSerializer类中的所有带注释的字段

时间:2015-10-27 02:39:18

标签: java jackson

我已经编写了我的CustomJsonSerializer,我希望它能自动序列化所有使用@JsonProperty注释的字段,所以我只会将那些没有注释的字段序列化,需要特别注意"

例如:我有Pojo

class Player {

@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));
    }
}

1 个答案:

答案 0 :(得分:1)

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));
    }
}

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

 class Player {

         @JsonProperty(user_id)
         private long userId;

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

如上所述 Jackson JSON custom serialization for certain fields

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));
    }
}

仅将序列化程序用于历史记录字段

curl_exec($ch);