faraz khonsari
faraz khonsari

Reputation: 1954

Gson change default Boolean Value to false if the field doesn't exist in json

I have model like this

public class testModel {

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

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

and a json like this

{
"test2":{}
}

when i parse this json with Gson

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

and the log is:

E/test: true false 

testModel.a is 'true' but testmodel.test2.b is 'false' why Gson changed the default value of b while b is not exist in json? what is the difference between b and a?

is it a Gson bug?

Upvotes: 3

Views: 2848

Answers (1)

faraz khonsari
faraz khonsari

Reputation: 1954

I asked my question in github https://github.com/google/gson/issues/1168 and a member answered correctly.

answer:

TestModel has a no-arg constructor while Test2 implicitly has one that takes an instance of TestModel. Mark Test2 as a static class and it will work.

Upvotes: 1

Related Questions