Nested classes in Gson

40 views Asked by At

I am new to Gson and I have a json response from an api that is nested. I created nested classes -

public class GsOrgIds {
    
    public GsOrgIdsData data;
    public String msg;
    public int retCode;
    
}

public class GsOrgIdsData {
    public int pageNum;
    public int pageSize;
    public int pages;
    public int total;
    public List<GsOrgIdsResult> result;
}

public class GsOrgIdsResult {
    public long createTime;
    public boolean isDefault;
    public String description;
    public String organization;
    public int id;
}

and when I try to read it -

GsOrgIds value = new Gson().fromJson(response, GsOrgIds.class);

I get

com.google.gson.JsonIOException: Failed making field 'gsapi.GsOrgIds#data' accessible; either increase its visibility or write a custom TypeAdapter for its declaring type.
    

Here is a example json -

{
    "data": {
        "result": [
            {
                "id": 49,
                "organization": "Default1",
                "description": "",
                "isDefault": 1,
                "createTime": 1565074728000
            },
            {
                "id": 118,
                "organization": "1",
                "description": "2",
                "isDefault": 0,
                "createTime": 1565158013000
            }
        ],
        "total": 8,
        "pages": 1,
        "pageSize": 30,
        "pageNum": 1
    },
    "msg": "",
    "retCode": 0
}

Do I have to write complete deserialization or is there a simpler way to get Gson to see the nested classes? Thanks!

1

There are 1 answers

0
Marcono1234 On BEST ANSWER

Gson uses reflection to access the fields of your classes. Therefore if your project is using a module-info.java file you have to configure it to allow reflective access by Gson.
This can be done by specifying opens <package-name> to com.google.gson:

module mymodule {
    requires com.google.gson;

    opens mypackage to com.google.gson;
}

Alternatively you can also write open module mymodule { /* ... */ } which opens all packages to all modules at runtime.

See the Gson Troubleshooting Guide and Understanding Java 9 Modules for more information.

And since you mentioned that you have created "nested classes", make sure that these classes are static. Otherwise they do not have a default no-args constructor and Gson falls back to using JDK internals for creating instances, which can be error-prone, see also GsonBuilder.disableJdkUnsafe().