From d8d8ccb98a80108d4f08f7f5e92a4af5f757a27e Mon Sep 17 00:00:00 2001 From: Eric Cochran Date: Mon, 30 Jul 2018 10:43:52 -0700 Subject: [PATCH] Simplify maintainType logic When we maintain the label value, we do not need to make a new JsonObject and copy over the keys and values when writing. The ordering will change, though. Before this change, it always put the label first. --- .../RuntimeTypeAdapterFactory.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java b/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java index 45d143aa..979860ec 100644 --- a/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java +++ b/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java @@ -241,15 +241,19 @@ public final class RuntimeTypeAdapterFactory implements TypeAdapterFactory { + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); - JsonObject clone = new JsonObject(); - - if (!maintainType) { - if (jsonObject.has(typeFieldName)) { - throw new JsonParseException("cannot serialize " + srcType.getName() - + " because it already defines a field named " + typeFieldName); - } - clone.add(typeFieldName, new JsonPrimitive(label)); + + if (maintainType) { + Streams.write(jsonObject, out); + return; } + + JsonObject clone = new JsonObject(); + + if (jsonObject.has(typeFieldName)) { + throw new JsonParseException("cannot serialize " + srcType.getName() + + " because it already defines a field named " + typeFieldName); + } + clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue());