GSON如果类中的对象为空/为null则跳过该类

huangapple go评论116阅读模式
英文:

GSON skip class if object in class is empty/null

问题

我正在为我的 Discord 机器人编写权限系统。
我面临的问题是 JSON 数据中出现了很多“空”对象。

我想要跳过这样的对象:

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

但要保留这样的对象:

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

我尝试使用 ExclusionStrategy => shouldSkipClass(Class<?> aClass),在该方法中检查该类的内容。像这样:

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

但这行不通,因为我只能获得类的类型,无法进行强制转换。

有人可以指导我正确的方向吗?
(请友善对待我,我白天是医护人员,编程只是业余爱好)

英文:

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

        &quot;userId&quot;: {
          &quot;userName&quot;: &quot;RandomDiscord Name&quot;,
          &quot;permissions&quot;: []
        },

But keep objects like these

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

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

@Override
public boolean shouldSkipClass(Class&lt;?&gt; 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)

答案1

得分: 1

Okay, I found a way to do 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.

英文:

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&lt;PermissionUser&gt; {
    @Override
    public JsonElement serialize(PermissionUser src, Type typeOfSrc, JsonSerializationContext context) {
        if(!src.getPermissions().isEmpty() &amp;&amp; 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.

huangapple
  • 本文由 发表于 2020年8月18日 22:31:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63470849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定