http-api: encode json Colors as ARGB hex codes

This commit is contained in:
Max Weber
2021-02-24 10:20:52 -07:00
committed by Adam
parent 48ea01dd28
commit 463b0d73ba
2 changed files with 25 additions and 9 deletions

View File

@@ -43,10 +43,7 @@ public class ColorTypeAdapter extends TypeAdapter<Color>
} }
int rgba = value.getRGB(); int rgba = value.getRGB();
out.beginObject() out.value(String.format("#%08X", rgba));
.name("value")
.value(rgba)
.endObject();
} }
@Override @Override
@@ -57,7 +54,18 @@ public class ColorTypeAdapter extends TypeAdapter<Color>
case NULL: case NULL:
in.nextNull(); in.nextNull();
return null; return null;
case STRING:
{
String value = in.nextString();
if (value.charAt(0) == '#')
{
value = value.substring(1);
}
int intValue = Integer.parseUnsignedInt(value, 16);
return new Color(intValue, true);
}
case BEGIN_OBJECT: case BEGIN_OBJECT:
{
in.beginObject(); in.beginObject();
double value = 0; double value = 0;
while (in.peek() != JsonToken.END_OBJECT) while (in.peek() != JsonToken.END_OBJECT)
@@ -74,6 +82,7 @@ public class ColorTypeAdapter extends TypeAdapter<Color>
} }
in.endObject(); in.endObject();
return new Color((int) value, true); return new Color((int) value, true);
}
} }
return null; // throws return null; // throws
} }

View File

@@ -34,17 +34,24 @@ public class ColorTypeAdapterTest
@Test @Test
public void test() public void test()
{ {
test("null", null); test("null", null, true);
test("{\"value\":-13347208,\"falpha\":0.0}", new Color(0x12345678, false)); test("{\"value\":-13347208,\"falpha\":0.0}", new Color(0x12345678, false), false);
test("{\"value\":305419896,\"falpha\":0.0}", new Color(0x12345678, true)); test("{\"value\":305419896,\"falpha\":0.0}", new Color(0x12345678, true), false);
test("{\"value\":-1.4221317E7,\"falpha\":0.0}", new Color(0xFF26FFFB, true)); test("{\"value\":-1.4221317E7,\"falpha\":0.0}", new Color(0xFF26FFFB, true), false);
test("\"#FF345678\"", new Color(0x12345678, false), true);
test("\"#12345678\"", new Color(0x12345678, true), true);
test("\"#FF26FFFB\"", new Color(0xFF26FFFB, true), true);
} }
private void test(String json, Color object) private void test(String json, Color object, boolean exactEncoding)
{ {
Color parsed = RuneLiteAPI.GSON.fromJson(json, Color.class); Color parsed = RuneLiteAPI.GSON.fromJson(json, Color.class);
Assert.assertEquals(object, parsed); Assert.assertEquals(object, parsed);
String serialized = RuneLiteAPI.GSON.toJson(object); String serialized = RuneLiteAPI.GSON.toJson(object);
if (exactEncoding)
{
Assert.assertEquals(json, serialized);
}
Color roundTripped = RuneLiteAPI.GSON.fromJson(serialized, Color.class); Color roundTripped = RuneLiteAPI.GSON.fromJson(serialized, Color.class);
Assert.assertEquals(object, roundTripped); Assert.assertEquals(object, roundTripped);
} }