如何在将对象转换为字符串时动态决定 json 项?

How can I dynamically decide on json items while converting an object to a string?

我需要在创建 json 字符串时动态包含字段。 目前,我可以使用 gson.toJson() 函数获取包含所有字段的 json 字符串。但在我的项目中,我可能需要在创建 json 字符串时避开某个字段。任何人都可以建议一种方法吗?

目前我有一个 class 如下:

class XXX {
    int a;
    int b;
    int c;
}

我用

Gson gson_obd =new Gson();
String Json_final= gson_obd.toJson(new XXX());

获取完整的 json 字符串。但是如何在创建 json 字符串时避免字段 b 呢?

您可以添加排除策略并在 Gson 解析器中为序列化过程注册它。

class MyExclusionStrategy implements ExclusionStrategy {
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        //skip all b fields from the XXX class
        return f.getName().equals("b") && f.getDeclaringClass() == XXX.class;
    }
    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}

String json = 
    new GsonBuilder().addSerializationExclusionStrategy(new MyExclusionStrategy()) 
                     .setPrettyPrinting()
                     .create()
                     .toJson(new XXX());

输出:

{
  "a": 0,
  "c": 0
}

我添加了 && f.getDeclaringClass() == XXX.class; 以确保您只跳过 XXX class 中的 "b" 字段。如果 XXX 包含一个 Foo 实例作为 "b" 字段,它不会被跳过。