-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathJsonObjectConverter.java
44 lines (37 loc) · 1.79 KB
/
JsonObjectConverter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* __ __ __ __ __ ___
* \ \ / / \ \ / / __/
* \ \/ / /\ \ \/ / /
* \____/__/ \__\____/__/.ɪᴏ
* ᶜᵒᵖʸʳᶦᵍʰᵗ ᵇʸ ᵛᵃᵛʳ ⁻ ˡᶦᶜᵉⁿˢᵉᵈ ᵘⁿᵈᵉʳ ᵗʰᵉ ᵃᵖᵃᶜʰᵉ ˡᶦᶜᵉⁿˢᵉ ᵛᵉʳˢᶦᵒⁿ ᵗʷᵒ ᵈᵒᵗ ᶻᵉʳᵒ
*/
package io.vavr.gson;
import com.google.gson.*;
import io.vavr.collection.Map;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
abstract class JsonObjectConverter<T> implements JsonSerializer<T>, JsonDeserializer<T> {
private static final Type[] EMPTY_TYPES = new Type[0];
abstract T fromJsonObject(JsonObject arr, Type type, Type[] subTypes, JsonDeserializationContext ctx) throws JsonParseException;
abstract Map<?, ?> toMap(T src);
@Override
public T deserialize(JsonElement json, Type type, JsonDeserializationContext ctx) throws JsonParseException {
if (json.isJsonObject()) {
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type[] types = parameterizedType.getActualTypeArguments();
return fromJsonObject(json.getAsJsonObject(), type, types, ctx);
} else {
return fromJsonObject(json.getAsJsonObject(), type, EMPTY_TYPES, ctx);
}
} else {
throw new JsonParseException("object expected");
}
}
@Override
public JsonElement serialize(T src, Type type, JsonSerializationContext ctx) {
return toMap(src).foldLeft(new JsonObject(), (a, e) -> {
a.add(ctx.serialize(e._1).getAsString(), ctx.serialize(e._2));
return a;
});
}
}