YanfeiGeng / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Deserialization with Gson.fromJson() should *ignore* missing fields #513

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?

1. Create a simple *non-static* class which initializes default values for some 
fields:

    public class Test {

        int x = -1;
        String s = "Hello";
    }

2. Create new Gson and call `fromJson()` with missing fields:

    Test t = new Gson().fromJson("{}", Test.class);
    System.out.println(String.format("x=[%s] s=[%s]", t.x, t.s));

>> Results: x=[0] s=[null]

    Test t = new Gson().fromJson("{\"x\": 1}", Test.class);
    System.out.println(String.format("x=[%s] s=[%s]", t.x, t.s));

>> Results: x=[1] s=[null]

What is the expected output? What do you see instead?

As the test cases, I would like to expect default value for each field to be 
the one that the class initializes. For instance with the first test case, `x` 
should be `-1` and `s` should be "Hello".

What version of the product are you using? On what operating system?

 - Gson 2.2.3
 - OSes:
   + Fedora 18, 64 bit with OpenJDK 1.7.0_19;
   + Android API 4 and API 17;

Thanks,
Hai

Original issue reported on code.google.com by haibison...@gmail.com on 5 May 2013 at 8:23

GoogleCodeExporter commented 9 years ago
Is this still an issue.  Did u try it in 2.2.4?

Its working for me on Windows with GSON 2.2.4

Original comment by haripr...@gmail.com on 3 Aug 2013 at 1:22

GoogleCodeExporter commented 9 years ago
Hari,

Yes it is. I've just tested with Gson 2.2.4 on Fedora 19, 64 bit with OpenJDK 
64-Bit Server VM (build 23.7-b01, mixed mode).

Original comment by haibison...@gmail.com on 4 Aug 2013 at 11:35

GoogleCodeExporter commented 9 years ago
Apparently, if you have a default constructor for the class, it will work as 
you like.

public Test() { }

and that should be enough for the instance variables to be initialized as 
declared.

Original comment by krt...@gmail.com on 22 Nov 2013 at 1:12

GoogleCodeExporter commented 9 years ago
@krt...

Thanks for your help. Unfortunately it's not working. I still got "x=[0] 
s=[null]". Gson v2.2.4.

Original comment by haibison...@gmail.com on 22 Nov 2013 at 7:28

GoogleCodeExporter commented 9 years ago
Confirm, this is still not working.
No way to assign default values for fields.
If field is missing in JSON it is deserialized as null.
Gson v2.2.4

Original comment by kamui.ji...@gmail.com on 31 Jan 2014 at 7:16

GoogleCodeExporter commented 9 years ago
This is most probably related to issue 495, see the links in the posting from 
Jun 23, 2013.

Original comment by Maaarti...@gmail.com on 2 Feb 2014 at 12:32