-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Closed
Milestone
Description
Below is a test case where I create a custom serializer and use it to serialize an object 1) in a HashMap and 2) in an ObjectNode. In both cases I pass attribute to the serializer like this:
mapper.writer().withAttribute("myAttr", "Hello!")
Serializing HashMap works as expected, but during ObjectNode serialization the attribute is null . It seems that in both cases the custom serializer should get access to the passed attribute and so both lines in the output should contain "Hello!"
Produced output from running testCase.test()
{"data":{"aStr":"The value is: Hello!"}}
{"data":{"aStr":"The value is: NULL"}}
Test case:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class TestCase {
public final static ObjectMapper mapper = new ObjectMapper();
@JsonSerialize(using = TestCase.CustomSer.class)
public static class Data {
public String aStr;
}
public static class CustomSer extends StdSerializer<Data> {
public CustomSer() {
super(Data.class);
}
@Override
public void serialize(Data value, JsonGenerator gen, SerializerProvider provider) throws IOException {
String attrStr = (String) provider.getAttribute("myAttr");
gen.writeStartObject();
gen.writeObjectField("aStr", "The value is: " + (attrStr == null ? "NULL" : attrStr));
gen.writeEndObject();
}
}
public static void test() throws IOException {
Data data = new Data();
data.aStr = "Hello";
Map<String, Object> mapTest = new HashMap<>();
mapTest.put("data", data);
ObjectNode treeTest = mapper.createObjectNode();
treeTest.putPOJO("data", data);
String mapOut = mapper.writer().withAttribute("myAttr", "Hello!").writeValueAsString(mapTest);
System.out.println(mapOut);
String treeOut = mapper.writer().withAttribute("myAttr", "Hello!").writeValueAsString(treeTest);
System.out.println(treeOut);
}
}
Metadata
Metadata
Assignees
Labels
No labels