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.
This commit is contained in:
Eric Cochran 2018-07-30 10:43:52 -07:00 committed by Jake Wharton
parent c1e7e2d280
commit d8d8ccb98a

View File

@ -241,15 +241,19 @@ public final class RuntimeTypeAdapterFactory<T> 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<String, JsonElement> e : jsonObject.entrySet()) {
clone.add(e.getKey(), e.getValue());