【问题标题】:Gson change default Boolean Value to false if the field doesn't exist in json如果 json 中不存在该字段,则 Gson 将默认布尔值更改为 false
【发布时间】:2017-10-11 08:39:11
【问题描述】:

我有这样的模型

public class testModel {

    public boolean a = true;
    public Test2 test2 = new Test2();

    public class Test2 {
        public boolean b = true;
    }
}

还有这样的json

{
"test2":{}
}

当我用 Gson 解析这个 json 时

testModel testModel = new Gson().fromJson("{ \"test2\":{}}", testModel.class);
    Log.e("test", testModel.a + " " + testModel.test2.b);

日志是:

E/test: true false 

testModel.a 为“真”,但 testmodel.test2.b 为“假” 为什么 Gson 更改了 b 的默认值,而 b 在 json 中不存在? b和a有什么区别?

这是一个 Gson 错误吗?

【问题讨论】:

  • 没有。我自己测试了一下,a和b都是假的
  • @SamuelRobert 你的 Gson 版本是什么?
  • 版本2.8.0; com.google.code.gson:gson:2.8.0
  • @SamuelRobert 我刚刚用 2.8.0 进行了测试,但我得到了真和假。我在实际项目中也有同样的问题。

标签: android gson


【解决方案1】:

我在 github https://github.com/google/gson/issues/1168 中问了我的问题,一位成员回答正确。

答案:

TestModel 有一个无参数构造函数,而 Test2 隐式有一个 接受 TestModel 的一个实例。将 Test2 标记为静态类,它将 工作。

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 1970-01-01
    • 2014-03-21
    • 2014-03-03
    • 2015-01-11
    • 2012-10-29
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多