|
3 | 3 |
|
4 | 4 | package net.servicestack.client;
|
5 | 5 |
|
| 6 | +import com.google.gson.Gson; |
6 | 7 | import com.google.gson.JsonDeserializationContext;
|
7 | 8 | import com.google.gson.JsonDeserializer;
|
8 | 9 | import com.google.gson.JsonElement;
|
9 | 10 | import com.google.gson.JsonParseException;
|
10 | 11 | import com.google.gson.JsonPrimitive;
|
11 | 12 | import com.google.gson.JsonSerializationContext;
|
12 | 13 | import com.google.gson.JsonSerializer;
|
| 14 | +import com.google.gson.TypeAdapter; |
| 15 | +import com.google.gson.TypeAdapterFactory; |
| 16 | +import com.google.gson.reflect.TypeToken; |
| 17 | +import com.google.gson.stream.JsonReader; |
| 18 | +import com.google.gson.stream.JsonToken; |
| 19 | +import com.google.gson.stream.JsonWriter; |
13 | 20 |
|
| 21 | +import java.io.IOException; |
14 | 22 | import java.lang.reflect.Type;
|
15 | 23 | import java.util.Date;
|
| 24 | +import java.util.HashMap; |
| 25 | +import java.util.Locale; |
| 26 | +import java.util.Map; |
16 | 27 | import java.util.UUID;
|
17 | 28 |
|
18 | 29 | public class JsonSerializers {
|
@@ -69,4 +80,45 @@ public UUID deserialize(JsonElement json, Type typeOfT, JsonDeserializationConte
|
69 | 80 | }
|
70 | 81 | };
|
71 | 82 | }
|
| 83 | + |
| 84 | + public static class CaseInsensitiveEnumTypeAdapterFactory implements TypeAdapterFactory { |
| 85 | + public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { |
| 86 | + Class<T> rawType = (Class<T>) type.getRawType(); |
| 87 | + if (!rawType.isEnum()) { |
| 88 | + return null; |
| 89 | + } |
| 90 | + |
| 91 | + final Map<String, T> lowercaseToConstant = new HashMap<String, T>(); |
| 92 | + for (T constant : rawType.getEnumConstants()) { |
| 93 | + lowercaseToConstant.put(toLowercase(constant), constant); |
| 94 | + } |
| 95 | + |
| 96 | + return new TypeAdapter<T>() { |
| 97 | + public void write(JsonWriter out, T value) throws IOException { |
| 98 | + if (value == null) { |
| 99 | + out.nullValue(); |
| 100 | + } else { |
| 101 | + out.value(value.toString()); |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + public T read(JsonReader reader) throws IOException { |
| 106 | + if (reader.peek() == JsonToken.NULL) { |
| 107 | + reader.nextNull(); |
| 108 | + return null; |
| 109 | + } else { |
| 110 | + return lowercaseToConstant.get(toLowercase(reader.nextString())); |
| 111 | + } |
| 112 | + } |
| 113 | + }; |
| 114 | + } |
| 115 | + |
| 116 | + private String toLowercase(Object o) { |
| 117 | + return o.toString().toLowerCase(Locale.US); |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + public static TypeAdapterFactory getCaseInsensitiveEnumTypeAdapterFactory() { |
| 122 | + return new CaseInsensitiveEnumTypeAdapterFactory(); |
| 123 | + } |
72 | 124 | }
|
0 commit comments