spkesDE
spkesDE

Reputation: 21

GSON skip class if object in class is empty/null

I'm currently writing a permission system for my discord bot. The problem that I'm facing is that the JSON gets quite full of "empty" objects.

I want to skip objects like these

        "userId": {
          "userName": "RandomDiscord Name",
          "permissions": []
        },

But keep objects like these

        "userId": {
          "userName": "RandomDiscord Name",
          "permissions": [
                "some.permission.string",
                "some.permission.string2",
                "some.permission.string3",
          ]
        },

I try to get a ExclusionStrategy => shouldSkipClass(Class<?> aClass) where I can check for the content for the that said class. Like

@Override
public boolean shouldSkipClass(Class<?> aClass) {
    if(aClass instanceof PermissionUser){
        PermissionUser user = (PermissionUser) aClass;
        return user.getPermissions().isEmpty();
    }
    return false;
}

But this won't work since I won't get the instance, only type of class, so I can't cast it.

Can anyone point me in the right direction? (Be nice to me, paramedic by daytime, programming only as a hobby)

Upvotes: 1

Views: 302

Answers (1)

spkesDE
spkesDE

Reputation: 21

Okay, I found a way todo this.

 Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
                .registerTypeAdapter(PermissionUser.class, new PermissionUserAdapter())
                .registerTypeAdapter(PermissionGroup.class, new PermissionGroupAdapter())
                .setPrettyPrinting().create();

The adapter looks like this.

public class PermissionUserAdapter implements JsonSerializer<PermissionUser> {
    @Override
    public JsonElement serialize(PermissionUser src, Type typeOfSrc, JsonSerializationContext context) {
        if(!src.getPermissions().isEmpty() && src.getPermissions() != null){
            Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
            return gson.toJsonTree(src);
        }
        return null;
    }
}

Quite simple once I got the right direction. If anybody has a better Idea, feel free to correct me.

Upvotes: 1

Related Questions