Skip to content

Commit fc119d1

Browse files
committed
Fix JSON serialization of java.awt.Color
1 parent 569f2be commit fc119d1

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

EnrichmentMapPlugin/src/main/java/org/baderlab/csplugins/enrichmentmap/model/io/ModelSerializer.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package org.baderlab.csplugins.enrichmentmap.model.io;
22

3+
import java.awt.Color;
34
import java.lang.reflect.Type;
45
import java.nio.file.Path;
56
import java.nio.file.Paths;
@@ -50,6 +51,7 @@ public static String serialize(EnrichmentMap map, boolean pretty) {
5051
GsonBuilder builder = new GsonBuilder()
5152
.registerTypeHierarchyAdapter(Path.class, new PathAdapter())
5253
.registerTypeAdapter(EnrichmentResult.class, new EnrichmentResultAdapter())
54+
.registerTypeHierarchyAdapter(Color.class, new ColorAdapter())
5355
.serializeSpecialFloatingPointValues(); // really important, we allow NaN in expression files
5456

5557
if (pretty) {
@@ -68,6 +70,7 @@ public static EnrichmentMap deserialize(String json) {
6870
.registerTypeAdapter(BiMap.class, new BiMapAdapter())
6971
.registerTypeHierarchyAdapter(Path.class, new PathAdapter())
7072
.registerTypeAdapter(EnrichmentResult.class, new EnrichmentResultAdapter())
73+
.registerTypeHierarchyAdapter(Color.class, new ColorAdapter())
7174
.registerTypeAdapter(immutableIntSetType, new ImmutableIntSetAdapter()).create();
7275

7376
try {
@@ -123,6 +126,31 @@ public JsonElement serialize(Path path, Type type, JsonSerializationContext cont
123126
return new JsonPrimitive(path.toString());
124127
}
125128
}
129+
130+
public static class ColorAdapter implements JsonDeserializer<Color>, JsonSerializer<Color> {
131+
@Override
132+
public Color deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) {
133+
int rgba = Color.GRAY.getRGB();
134+
try {
135+
if(jsonElement.isJsonObject()) {
136+
JsonObject jsonObject = jsonElement.getAsJsonObject();
137+
JsonElement element = jsonObject.get("value");
138+
rgba = element.getAsInt();
139+
} else if(jsonElement.isJsonPrimitive()) {
140+
rgba = jsonElement.getAsInt();
141+
}
142+
} catch(Exception e) { }
143+
144+
return new Color(rgba, true);
145+
}
146+
147+
@Override
148+
public JsonElement serialize(Color color, Type type, JsonSerializationContext context) {
149+
JsonObject obj = new JsonObject();
150+
obj.add("value", new JsonPrimitive(color.getRGB()));
151+
return obj;
152+
}
153+
}
126154

127155
// Note: This can be solved with RuntimeTypeAdapterFactory, but its not part of
128156
// the default GSON distribution

0 commit comments

Comments
 (0)