blob: 98105631d79334189f92faf9a6cc2a906afa0b6e [file] [log] [blame]
Jonathan Hart77803d32014-08-19 08:53:00 -07001package net.floodlightcontroller.restserver;
2
3import org.codehaus.jackson.Version;
4import org.codehaus.jackson.map.JsonSerializer;
5import org.codehaus.jackson.map.ObjectMapper;
6import org.codehaus.jackson.map.module.SimpleModule;
7import org.codehaus.jackson.map.ser.CustomSerializerFactory;
8import org.restlet.ext.jackson.JacksonRepresentation;
9import org.restlet.representation.Representation;
10
11/**
12 * Helper class used to dynamically override the default serializers used for
13 * JSON serialization.
14 * <p/>
15 * Serializers can be added to the helper class at runtime using
16 * {@link #addSerializer(Class, JsonSerializer)}. The serializers contained by
17 * the helper class can then be added to a JacksonRepresentation prior to
18 * serializing it using {@link #applySerializers(JacksonRepresentation)}.
19 * <p/>
20 * This class enables the use of custom serializers for Java objects without
21 * having to hardcode the mapping of class to serializer using
22 * annotations on the class. Any serialization annotations on the class will be
23 * overridden by the serializers used here, so different serializers can be
24 * used on the class in different contexts.
25 */
26public class CustomSerializerHelper {
27 private final ObjectMapper mapper;
28 private final SimpleModule customSerializerModule;
29 private CustomSerializerFactory sf;
30
31 /**
32 * Constructor.
33 */
34 public CustomSerializerHelper() {
35 mapper = new ObjectMapper();
36 customSerializerModule = new SimpleModule("custom-serializers", new Version(1, 0, 0, null));
37 mapper.registerModule(customSerializerModule);
38 sf = new CustomSerializerFactory();
39 }
40
41 /**
42 * Adds a serializer to the set of serializers that will be used for JSON
43 * serialization.
44 *
45 * @param serializer the serializer to add
46 */
47 public <T> void addSerializer(Class<T> clazz, JsonSerializer<T> serializer) {
48 customSerializerModule.addSerializer(serializer);
49 sf.addGenericMapping(clazz, serializer);
50 }
51
52 /**
53 * Applies the list of serializers to the JacksonRepresentation so they
54 * will be used when the object in the representation is serialized
55 *
56 * @param jacksonRepresentation the representation to apply the serializers
57 * to
58 * @return a representation with the custom serializers applied
59 */
60 public Representation applySerializers(JacksonRepresentation<?> jacksonRepresentation) {
61 mapper.registerModule(customSerializerModule);
62 jacksonRepresentation.setObjectMapper(mapper);
63 mapper.setSerializerFactory(sf);
64 return jacksonRepresentation;
65 }
66}