forked from graphql-java/graphql-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonKit.java
More file actions
38 lines (33 loc) · 1.29 KB
/
JsonKit.java
File metadata and controls
38 lines (33 loc) · 1.29 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
package example.http;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import graphql.ExecutionResult;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
/**
* This example code chose to use GSON as its JSON parser. Any JSON parser should be fine
*/
public class JsonKit {
static final Gson GSON = new GsonBuilder()
//
// This is important because the graphql spec says that null values should be present
//
.serializeNulls()
.create();
public static void toJson(HttpServletResponse response, ExecutionResult executionResult) throws IOException {
GSON.toJson(executionResult, response.getWriter());
}
public static Map<String, Object> toMap(String jsonStr) {
if (jsonStr == null || jsonStr.trim().length() == 0) {
return Collections.emptyMap();
}
// gson uses type tokens for generic input like Map<String,Object>
TypeToken<Map<String, Object>> typeToken = new TypeToken<Map<String, Object>>() {
};
Map<String, Object> map = GSON.fromJson(jsonStr, typeToken.getType());
return map == null ? Collections.emptyMap() : map;
}
}