http-api: encode json Instants as millis since epoch

This commit is contained in:
Max Weber
2021-02-24 10:21:31 -07:00
committed by Adam
parent 463b0d73ba
commit 06b8e1b798
3 changed files with 17 additions and 10 deletions

View File

@@ -43,12 +43,7 @@ public class InstantTypeAdapter extends TypeAdapter<Instant>
return;
}
out.beginObject()
.name("seconds")
.value(value.getEpochSecond())
.name("nanos")
.value(value.getNano())
.endObject();
out.value(value.toEpochMilli());
}
@Override
@@ -60,6 +55,12 @@ public class InstantTypeAdapter extends TypeAdapter<Instant>
return null;
}
if (in.peek() == JsonToken.NUMBER)
{
long jsTime = in.nextLong();
return Instant.ofEpochMilli(jsTime);
}
long seconds = 0;
int nanos = 0;
in.beginObject();

View File

@@ -34,15 +34,20 @@ public class InstantTypeAdapterTest
@Test
public void test()
{
test("null", null);
test("{\"seconds\":1609538310,\"nanos\":291698903}", Instant.ofEpochSecond(1609538310, 291698903));
test("null", null, true);
test("{\"seconds\":1609538310,\"nanos\":291000000}", Instant.ofEpochSecond(1609538310, 291_000_000), false);
test("1609538310291", Instant.ofEpochSecond(1609538310, 291_000_000), true);
}
private void test(String json, Instant object)
private void test(String json, Instant object, boolean exactEncoding)
{
Instant parsed = RuneLiteAPI.GSON.fromJson(json, Instant.class);
Assert.assertEquals(object, parsed);
String serialized = RuneLiteAPI.GSON.toJson(object);
if (exactEncoding)
{
Assert.assertEquals(json, serialized);
}
Instant roundTripped = RuneLiteAPI.GSON.fromJson(serialized, Instant.class);
Assert.assertEquals(object, roundTripped);
}