forked from meilisearch/meilisearch-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGsonJsonHandler.java
More file actions
59 lines (52 loc) · 1.97 KB
/
GsonJsonHandler.java
File metadata and controls
59 lines (52 loc) · 1.97 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.meilisearch.sdk.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.meilisearch.sdk.exceptions.JsonDecodingException;
import com.meilisearch.sdk.exceptions.JsonEncodingException;
import com.meilisearch.sdk.exceptions.MeilisearchException;
import com.meilisearch.sdk.model.FilterableAttribute;
import com.meilisearch.sdk.model.Key;
public class GsonJsonHandler implements JsonHandler {
private final Gson gson;
public GsonJsonHandler() {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Key.class, new GsonKeyTypeAdapter());
builder.registerTypeAdapter(
FilterableAttribute.class, new GsonFilterableAttributeSerializer());
this.gson = builder.create();
}
@Override
public String encode(Object o) throws MeilisearchException {
if (o != null && o.getClass() == String.class) {
return (String) o;
}
try {
return gson.toJson(o);
} catch (Exception e) {
throw new JsonEncodingException(e);
}
}
@Override
@SuppressWarnings("unchecked")
public <T> T decode(Object o, Class<T> targetClass, Class<?>... parameters)
throws MeilisearchException {
if (o == null) {
throw new JsonDecodingException("Response to deserialize is null");
}
if (targetClass == String.class) {
return (T) o;
}
try {
if (parameters == null || parameters.length == 0) {
return gson.fromJson((String) o, targetClass);
} else {
TypeToken<?> parameterized = TypeToken.getParameterized(targetClass, parameters);
return gson.fromJson((String) o, parameterized.getType());
}
} catch (JsonSyntaxException e) {
throw new JsonDecodingException(e);
}
}
}