【问题标题】:How to ignoring empty string during deserialization by GSON如何在 GSON 反序列化期间忽略空字符串
【发布时间】:2021-08-25 19:36:42
【问题描述】:

我想使用 GSON 中的 toJson 删除空字符串。 示例对象:

public class ExampleObject {
    String defaultEmpty = "";
    String example;

    public ExampleObject() {
        this.example = "foo";
    }

之后

使用

new Gson().toJson(new ExampleObject());

我收到了

  "defaultEmpty " : "",
   "position" : "foo"

有什么方法可以在反序列化过程中不包含空字符串?我知道 GSON 忽略了 null,但有时我的对象中有一个空字符串,我不得不忽略它。

【问题讨论】:

  • 如果您不希望默认toJson 的行为,请编写您自己的toJson。我不确定这个问题到底是什么意思。
  • @SilvioMayolo 我想跳过字符串结果中的空 json
  • 我读过那个,但这不是我所期望的。我无法操作模型 - 无论如何,谢谢!
  • 我的回答有帮助吗?

标签: java


【解决方案1】:

这是一个简化的例子。

static class ExampleObjectSerializer implements JsonSerializer<ExampleObject> {

    @Override
    public JsonElement serialize(ExampleObject src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject object = new JsonObject();
        object.addProperty("example", src.example);
        if(src.defaultEmpty != null && !src.defaultEmpty.equals("")) {
            object.addProperty("defaultEmpty", src.defaultEmpty);
        }
        return object;
    }
}

public static void main(String[] args) {
    Gson gson = new GsonBuilder().registerTypeAdapter(ExampleObject.class, new ExampleObjectSerializer()).create();
    ExampleObject exampleObject = new ExampleObject();
    String result = gson.toJson(exampleObject);
    System.out.println(result);
}

【讨论】:

    猜你喜欢
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 2016-06-23
    相关资源
    最近更新 更多