Project

General

Profile

1
package eu.dnetlib.pace.model;
2

    
3
import java.lang.reflect.Type;
4

    
5
import com.google.gson.Gson;
6
import com.google.gson.GsonBuilder;
7
import com.google.gson.InstanceCreator;
8
import com.google.gson.JsonDeserializationContext;
9
import com.google.gson.JsonDeserializer;
10
import com.google.gson.JsonElement;
11
import com.google.gson.JsonParseException;
12

    
13
/**
14
 * The Class MapDocumentSerializer.
15
 */
16
public class MapDocumentSerializer implements InstanceCreator<MapDocument> {
17

    
18
	@Override
19
	public MapDocument createInstance(final Type type) {
20
		return new MapDocument();
21
	}
22

    
23
	/**
24
	 * Decode.
25
	 *
26
	 * @param bytes
27
	 *            the bytes
28
	 * @return the map document
29
	 */
30
	public static MapDocument decode(final byte[] bytes) {
31

    
32
		GsonBuilder gson = new GsonBuilder();
33

    
34
		gson.registerTypeAdapter(Field.class, new JsonDeserializer<Field>() {
35

    
36
			@Override
37
			public Field deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
38
				FieldListImpl fl = new FieldListImpl();
39
				if (json.isJsonObject()) {
40
					String name = json.getAsJsonObject().get("name").getAsString();
41
					String type = json.getAsJsonObject().get("type").getAsString();
42
					String value = json.getAsJsonObject().get("value").getAsString();
43
					fl.add(new FieldValueImpl(eu.dnetlib.pace.config.Type.valueOf(type), name, value));
44
				}
45
				return fl;
46
			}
47
		});
48

    
49
		return gson.create().fromJson(new String(bytes), MapDocument.class);
50
	}
51

    
52
	/**
53
	 * To string.
54
	 *
55
	 * @param doc
56
	 *            the doc
57
	 * @return the string
58
	 */
59
	public static String toString(final MapDocument doc) {
60
		return new Gson().toJson(doc);
61
	}
62

    
63
	/**
64
	 * To byte array.
65
	 *
66
	 * @param doc
67
	 *            the doc
68
	 * @return the byte[]
69
	 */
70
	public static byte[] toByteArray(final MapDocument doc) {
71
		return toString(doc).getBytes();
72
	}
73

    
74
}
(14-14/16)