1 package com.fasterxml.jackson.databind.node;
2 
3 import java.io.IOException;
4 import java.util.*;
5 
6 import com.fasterxml.jackson.core.JsonGenerator;
7 import com.fasterxml.jackson.databind.*;
8 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
9 import com.fasterxml.jackson.databind.node.ObjectNode;
10 import com.fasterxml.jackson.databind.ser.std.StdSerializer;
11 
12 public class POJONodeTest extends NodeTestBase
13 {
14     @JsonSerialize(using = CustomSer.class)
15     public static class Data {
16       public String aStr;
17     }
18 
19     @SuppressWarnings("serial")
20     public static class CustomSer extends StdSerializer<Data> {
CustomSer()21       public CustomSer() {
22           super(Data.class);
23       }
24 
25       @Override
serialize(Data value, JsonGenerator gen, SerializerProvider provider)26       public void serialize(Data value, JsonGenerator gen, SerializerProvider provider) throws IOException {
27         String attrStr = (String) provider.getAttribute("myAttr");
28         gen.writeStartObject();
29         gen.writeStringField("aStr", "The value is: " + (attrStr == null ? "NULL" : attrStr));
30         gen.writeEndObject();
31       }
32     }
33 
34     final ObjectMapper MAPPER = newJsonMapper();
35 
testPOJONodeCustomSer()36     public void testPOJONodeCustomSer() throws Exception
37     {
38       Data data = new Data();
39       data.aStr = "Hello";
40 
41       Map<String, Object> mapTest = new HashMap<>();
42       mapTest.put("data", data);
43 
44       ObjectNode treeTest = MAPPER.createObjectNode();
45       treeTest.putPOJO("data", data);
46 
47       final String EXP = "{\"data\":{\"aStr\":\"The value is: Hello!\"}}";
48 
49       String mapOut = MAPPER.writer().withAttribute("myAttr", "Hello!").writeValueAsString(mapTest);
50       assertEquals(EXP, mapOut);
51 
52       String treeOut = MAPPER.writer().withAttribute("myAttr", "Hello!").writeValueAsString(treeTest);
53       assertEquals(EXP, treeOut);
54     }
55 }
56