mercredi 18 mars 2015

Spring Framework JSON Serialization to Array rather than Object

In my web application that is using Spring, we want use a custom JSON structure. Spring by default takes a POJO like this:



public class Model {

private int id;

public Model(){}

public Model(int id){
this.id = id;
}
}


and turns it into this:



{"id":1}


With our application, we want to turn it into this instead:



[1]


I want to use Spring's default serialization logic that detects the Java type and maps to the appropriate JSON type, but just change the wrapping object to an array rather than and object with fields.


This is the Serializer I have so far (which will be implemented in the model with @JsonSerialize(using = Serializer.class)), but would prefer not to rewrite all the logic Spring already has implemented.



public class Serializer extends JsonSerializer<Model> {
@Override
public void serialize(Model value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {

jgen.writeStartArray();
jgen.writeString(value.test);
jgen.writeEndArray();

}
}


How can I hook into the pre-existing Serializer?


Aucun commentaire:

Enregistrer un commentaire