【问题标题】:Android Google Gson convert object toJson is null valueAndroid Google Gson 将对象转换为Json 为空值
【发布时间】:2015-10-20 15:21:49
【问题描述】:

我正在使用谷歌 gson 2.4 版 我已将文件 gson-2.4.jar 添加到我在 Android Studio 中的 libs 文件夹下的 Android 项目中。代码构建成功。

我的代码如下

class Test{
        private final int id;
        private final String name;
        public Test(){
            id = 1;
            name = "Hello world";
        }
    }
    GsonBuilder gsonBuilder = new GsonBuilder();
    Test test = new Test();
    gsonBuilder.setPrettyPrinting().serializeNulls();
    Gson gson = gsonBuilder.create();

    String json = gson.toJson(test);
    System.out.print(json);

json 始终为空值。

我的预期结果为

{"id":1,"name":"Hello world"}

我该如何解决? 谢谢

【问题讨论】:

  • 你的意思是json 为空?
  • @Blackbelt,我的预期结果是 {"id":1,"name":"Hello world"}
  • 如果 json 为 null,System.out.print(json) 将使您的应用崩溃
  • 我以调试模式运行应用程序来查看 json 的值。 System.out.print(json) 行有一个断点; :D
  • 也许调试器没有评估变量。如果没有调试器运行它会崩溃吗?

标签: android serialization gson


【解决方案1】:

看起来你正在以另一种方式实现它,因为它应该......

class Test{
        private final int id;
        private final String name;
        public Test(){
            id = 1;
            name = "Hello world";
        }
    }

public String convertToJson(){
        Gson gson = new Gson();

        return  gson.toJson(this);
}

这应该会打印出您所期望的:

{"id":1,"name":"Hello world"}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 2016-08-07
    • 2021-10-04
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多