google / google/gson

When field is marked to be excluded from deserialization, it is still deserialized.

Open
#2,348 5 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

# Gson version 2.10

# Java 11

# Used tools Eclipse + Maven

# Description
I have added Exclusion strategy for deserialization of one field, and that strategy is ignored and Exception: declares multiple JSON fields named field is thrown.

## Expected behavior
I would expect that when strategy return true in method shouldSkipField, that the field will be ignored

## Actual behavior
Exception: declares multiple JSON fields named field is thrown because field is not ignored

# Reproduction steps
Create class and subclass with fields which share serialized name.
```
import com.google.gson.*;
import com.google.gson.annotations.SerializedName;

public class GSonTest
{
public static void main(String[] args)
{
GsonBuilder builder = new GsonBuilder();
builder.addDeserializationExclusionStrategy(new BaseDataExclusionStrategy());
SpecificClass specificClass = builder.create().fromJson("{\"data\":\"Test String\"}", SpecificClass.class);

}

public static class BaseClass
{
@SerializedName("data")
private Object data = null;
}

public static class SpecificClass extends BaseClass
{
@SerializedName("data")
private String concreteData = null;
}

private static class BaseDataExclusionStrategy implements ExclusionStrategy
{
@Override
public boolean shouldSkipClass(Class arg0)
{
return false;
}

@Override
public boolean shouldSkipField(FieldAttributes field)
{
return "data".equals(field.getName()) && Object.class.equals(field.getDeclaredClass());
}

}
}

```

# Exception stack trace

```
Exception in thread "main" java.lang.IllegalArgumentException: class GSonTest$SpecificClass declares multiple JSON fields named data
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:217)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:112)
at com.google.gson.Gson.getAdapter(Gson.java:531)
at com.google.gson.Gson.fromJson(Gson.java:1057)
at com.google.gson.Gson.fromJson(Gson.java:1016)
at com.google.gson.Gson.fromJson(Gson.java:959)
at com.google.gson.Gson.fromJson(Gson.java:927)
at GSonTest.main(GSonTest.java:16)
```

Code Snippet I think is reason for it:
https://github.com/google/gson/blob/26229d33d81f0d60f508411eb3c541f3e87322ac/gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java#L260
```
boolean serialize = includeField(field, true);
boolean deserialize = includeField(field, false);
if (!serialize && !deserialize) {
continue;
}
```
I think it should be here logical OR instead of AND

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.