Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Registering an ExclusionStrategy for deserialization affects serialized output #2190

Open
Marcono1234 opened this issue Sep 2, 2022 · 0 comments
Labels

Comments

@Marcono1234
Copy link
Collaborator

Marcono1234 commented Sep 2, 2022

Gson version

2.9.1

Java / Android version

Java 17

Description

Registering an ExclusionStrategy which excludes a subclass on deserialization affects the serialized output for that class.
The underlying issue is the same as for #1833 and #2032.

Maybe at this point there should be a method TypeAdapter.usesReflection() whose default implementation returns false but which can be overridden by subclasses. This would avoid all this special-casing, and it would also allow third-party adapters to make use of this.

Important: Fixing this might affect the exclusion handling for serialization, so maybe this cannot be solved easily.

Reproduction steps

static class Base {
}
static class Sub extends Base {
  int i = 0;
}
static class Container {
  Base b = new Sub();
}

@Test
public void test() {
  ExclusionStrategy exclusionStrategy = new ExclusionStrategy() {
    @Override public boolean shouldSkipField(FieldAttributes f) {
      return false;
    }

    @Override public boolean shouldSkipClass(Class<?> clazz) {
      return clazz == Sub.class;
    }
  };

  Gson gson = new GsonBuilder()
    .registerTypeAdapter(Base.class, new TypeAdapter<Base>() {
      @Override public Base read(JsonReader in) throws IOException {
        throw new AssertionError("not needed");
      }

      @Override public void write(JsonWriter out, Base value) throws IOException {
        out.value("custom-adapter");
      }
    })
    // Registering a *de*serialization exclusion affects serialization
    .addDeserializationExclusionStrategy(exclusionStrategy)
    .create();

  assertEquals("{\"b\":\"custom-adapter\"}", gson.toJson(new Container()));
}

When the ExclusionStrategy is registered, TypeAdapterRuntimeTypeWrapper erroneously considers the adapter created by Excluder (which wraps a reflective adapter) as non-reflective. The assertion above fails because the output is erroneously {"b":{"i":0}}.

@Marcono1234 Marcono1234 added the bug label Sep 2, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant