1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package net.anyflow.lannister.serialization;
18
19 import java.io.IOException;
20
21 import com.fasterxml.jackson.core.JsonFactory;
22 import com.fasterxml.jackson.databind.ObjectMapper;
23 import com.fasterxml.jackson.dataformat.smile.SmileFactory;
24 import com.hazelcast.nio.ObjectDataInput;
25 import com.hazelcast.nio.ObjectDataOutput;
26 import com.hazelcast.nio.serialization.Serializer;
27 import com.hazelcast.nio.serialization.StreamSerializer;
28
29 public final class JsonSerializer<T> extends HazelcastSerializer<T, ObjectMapper> implements StreamSerializer<T> {
30 public static final int TYPEID_JSON_PLAIN = 100;
31 public static final int TYPEID_JSON_BINARY = 101;
32
33 private JsonSerializer(Class<T> type, int typeId) {
34 this(type, typeId, null);
35 }
36
37 private JsonSerializer(Class<T> type, int typeId, final JsonFactory factory) {
38 super(type, typeId, () -> new ObjectMapper(factory));
39 }
40
41 @Override
42 public void write(ObjectDataOutput out, T object) throws IOException {
43 out.writeByteArray(get().writeValueAsBytes(object));
44 }
45
46 @Override
47 public T read(ObjectDataInput in) throws IOException {
48 return get().readValue(in.readByteArray(), getType());
49 }
50
51 public static <V> Serializer makeBinary(final Class<V> type) {
52 return new JsonSerializer<>(type, TYPEID_JSON_BINARY, new SmileFactory());
53 }
54
55 public static <V> Serializer makePlain(final Class<V> type) {
56 return new JsonSerializer<>(type, TYPEID_JSON_PLAIN);
57 }
58 }