I have to serialize JSON from a list of Objects. The resulting JSON has to look like this:
{
\"status\": \"success\",
\"models\": [
{
This is an oldish question, But there is an arguably more idiomatic way of implementing this (I'm using jackson-databind:2.8.8
):
Define a ModelSerializer
(That extends StdSerializer
as recommended by Jackson) that prints your model how you like and use the @JsonSerialize(contentUsing = ...)
over your collection type:
class ModelSerializer extends StdSerializer {
public ModelSerializer(){this(null);}
public ModelSerializer(Class t){super(t);} // sets `handledType` to the provided class
@Override
public void serialize(List value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
jgen.writeObjectField("model", value);
jgen.writeEndObject();
}
}
Meanwhile, in another file:
class SomethingWithModels {
// ...
@JsonSerialize(contentUsing = ModelSerializer.class)
private Collection models;
// ...
}
Now you aren't bound to just List
s of models but may apply this to Collection
s, Set
s, Native []
s and even the values of Map
s.