Project

General

Profile

1
package eu.dnetlib.pace.model;
2

    
3
import java.lang.reflect.Type;
4

    
5
import com.google.gson.GsonBuilder;
6
import com.google.gson.InstanceCreator;
7
import com.google.gson.JsonDeserializationContext;
8
import com.google.gson.JsonDeserializer;
9
import com.google.gson.JsonElement;
10
import com.google.gson.JsonObject;
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 s
27
	 *            the String
28
	 * @return the map document
29
	 */
30
	public static MapDocument decode(final String s) {
31
		final GsonBuilder gson = new GsonBuilder();
32

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

    
35
			@Override
36
			public Field deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
37
				final FieldListImpl fl = new FieldListImpl();
38
				if (json.isJsonObject()) {
39

    
40
					fl.add(handleJsonObject(json.getAsJsonObject()));
41

    
42
				} else if (json.isJsonArray()) {
43

    
44
					for (final JsonElement e : json.getAsJsonArray()) {
45
						if (e.isJsonObject()) {
46
							fl.add(handleJsonObject(e.getAsJsonObject()));
47
						}
48
					}
49
				}
50
				return fl;
51
			}
52

    
53
			private Field handleJsonObject(final JsonObject o) {
54
				final FieldListImpl fl = new FieldListImpl();
55
				final String name = o.get("name").getAsString();
56
				final String type = o.get("type").getAsString();
57
				final String value = o.get("value").getAsString();
58
				fl.add(new FieldValueImpl(eu.dnetlib.pace.config.Type.valueOf(type), name, value));
59
				return fl;
60
			}
61
		});
62

    
63
		return gson.create().fromJson(s, MapDocument.class);
64
	}
65

    
66
	/**
67
	 * Decode.
68
	 *
69
	 * @param bytes
70
	 *            the bytes
71
	 * @return the map document
72
	 */
73
	public static MapDocument decode(final byte[] bytes) {
74
		return decode(new String(bytes));
75
	}
76

    
77
	/**
78
	 * To string.
79
	 *
80
	 * @param doc
81
	 *            the doc
82
	 * @return the string
83
	 */
84
	public static String toString(final MapDocument doc) {
85
		final GsonBuilder b = new GsonBuilder();
86
		return b.setPrettyPrinting().create().toJson(doc);
87

    
88
	}
89

    
90
	/**
91
	 * To byte array.
92
	 *
93
	 * @param doc
94
	 *            the doc
95
	 * @return the byte[]
96
	 */
97
	public static byte[] toByteArray(final MapDocument doc) {
98
		return toString(doc).getBytes();
99
	}
100

    
101
}
(13-13/15)