Given the following class hierarchy, I would like Foo to be serialized differently depending on the context it is used in my class hierarchy.
public class Foo {
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Type;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.SerializerBase;
import org.junit.Test;
class Foo {
public String bar;
public String biz;
}
class FooContainer {
public Foo fooA;
@JsonSerialize(using = FooCustomSerializer.class)
public Foo fooB;
}
class FooCustomSerializer extends SerializerBase {
public FooCustomSerializer() {
super(Foo.class);
}
@Override
public void serialize(Foo foo, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonGenerationException {
generator.writeStartObject();
generator.writeObjectField("bar", foo.bar);
generator.writeEndObject();
}
@Override
public JsonNode getSchema(SerializerProvider arg0, Type arg1) throws JsonMappingException {
return null;
}
}
public class JacksonTest {
@Test
public void customField() throws Exception {
FooContainer object = new FooContainer();
object.fooA = new Foo();
object.fooA.bar = "asdf";
object.fooA.biz = "fdsa";
object.fooB = new Foo();
object.fooB.bar = "qwer";
object.fooB.biz = "test";
ObjectMapper mapper = new ObjectMapper();
StringWriter writer = new StringWriter();
mapper.writeValue(writer, object);
String expected = "{\"fooA\":{\"bar\":\"asdf\",\"biz\":\"fdsa\"},\"fooB\":{\"bar\":\"qwer\"}}";
assertEquals(expected, writer.toString());
}
}
Using @JsonSerialize(using = FooCustomSerializer.class) on the public Foo fooB; field.
http://jackson.codehaus.org/1.9.9/javadoc/org/codehaus/jackson/map/annotate/JsonSerialize.html