0

I've written my CustomJsonSerializer and I would like it to automatically serialize all fields that are annotated using @JsonProperty so I would only left serializing the ones which are not annotated and need "special care".

For example: I have the Pojo

class Player {

@JsonProperty(user_id)
private long userId;

private byte[] history;
}

My custom Serializer:

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));
    }
}
Shvalb
  • 1,835
  • 2
  • 30
  • 60

1 Answers1

1
   class Player {

     @JsonProperty(user_id)
     private long userId;

     @JsonIgnore
     private byte[] history;
    }

In your custom serializer call the parent serializer method so it would continue serialization.

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

Or As mentioned here Jackson JSON custom serialization for certain fields

 class Player {

         @JsonProperty(user_id)
         private long userId;

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

Use the the serializer only for the history field

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));
    }
}
Community
  • 1
  • 1
Deshan
  • 2,112
  • 25
  • 29