|
6 | 6 | import com.google.gson.stream.JsonReader;
|
7 | 7 | import com.google.gson.stream.JsonWriter;
|
8 | 8 | import java.io.IOException;
|
| 9 | +import org.unicode.cldr.util.CLDRLocale; |
9 | 10 |
|
10 | 11 | /** utilities for JSON */
|
11 | 12 | public class JsonUtil {
|
12 | 13 |
|
| 14 | + private abstract static class WriteOnlyTypeAdapter<T> extends TypeAdapter<T> { |
| 15 | + @Override |
| 16 | + public T read(JsonReader in) throws IOException { |
| 17 | + // write only |
| 18 | + throw new UnsupportedOperationException("Unimplemented method 'read' - write only"); |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + private static final class JSONStringTypeAdapter extends WriteOnlyTypeAdapter<JSONString> { |
| 23 | + @Override |
| 24 | + public void write(JsonWriter out, JSONString value) throws IOException { |
| 25 | + out.jsonValue(value.toJSONString()); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + /** type adapter that uses Object.toString() rather than serializing object contents */ |
| 30 | + private static final class ToStringTypeAdapter<T> extends WriteOnlyTypeAdapter<T> { |
| 31 | + @Override |
| 32 | + public void write(JsonWriter out, T value) throws IOException { |
| 33 | + out.value(value.toString()); |
| 34 | + } |
| 35 | + } |
| 36 | + |
13 | 37 | private static final Gson gson =
|
14 | 38 | new GsonBuilder()
|
15 | 39 | .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
|
16 | 40 | .setPrettyPrinting()
|
17 |
| - .registerTypeHierarchyAdapter( |
18 |
| - JSONString.class, |
19 |
| - new TypeAdapter<JSONString>() { |
20 |
| - |
21 |
| - @Override |
22 |
| - public void write(JsonWriter out, JSONString value) |
23 |
| - throws IOException { |
24 |
| - out.jsonValue(value.toJSONString()); |
25 |
| - } |
26 |
| - |
27 |
| - @Override |
28 |
| - public JSONString read(JsonReader in) throws IOException { |
29 |
| - // write only |
30 |
| - // TODO Auto-generated method stub |
31 |
| - throw new UnsupportedOperationException( |
32 |
| - "Unimplemented method 'read' - write only"); |
33 |
| - } |
34 |
| - }) |
| 41 | + // register any classes that need toString() for serialization |
| 42 | + .registerTypeHierarchyAdapter(CLDRLocale.class, new ToStringTypeAdapter<>()) |
| 43 | + .registerTypeHierarchyAdapter(JSONString.class, new JSONStringTypeAdapter()) |
35 | 44 | .create();
|
36 | 45 |
|
37 | 46 | public static Gson gson() {
|
|
0 commit comments