google / google/gson

Unable to deserialize a null property into a JsonObject

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

Description

Repro:

```java
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class GsonDeserialization {

public static void main(String... args) {
final Gson gson = new Gson();
// succeeds
final MyObject mo1 = gson.fromJson("{ \"name\": null, \"otherProperties\": {} }", MyObject.class);
// throws
final MyObject mo2 = gson.fromJson("{ \"name\": \"Alex\", \"otherProperties\": null }", MyObject.class);
}

public static class MyObject {
public String name;
public JsonObject otherProperties;
}
}
```
```
Exception in thread "main" com.google.gson.JsonSyntaxException: Expected a com.google.gson.JsonObject but was com.google.gson.JsonNull
at com.google.gson.internal.bind.TypeAdapters$35$1.read(TypeAdapters.java:896)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
at com.google.gson.Gson.fromJson(Gson.java:888)
at com.google.gson.Gson.fromJson(Gson.java:853)
at com.google.gson.Gson.fromJson(Gson.java:802)
at com.google.gson.Gson.fromJson(Gson.java:774)
at com.andrew.scratch.GsonDeserialization.main(GsonDeserialization.java:13)
```

I would expect the second example to deserialize into an object with a (java) null `otherProperties` member, but instead it throws a JsonSyntaxException.

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.