rohandalvi / google-gson

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

Double brace initialization screws up serialization #555

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
This code produces no output at all.
ArrayList<String> arrayList = new ArrayList<String>()
        {{
                add("A");
                add("B");
                add("C");
            }};
Gson gson = new Gson();
gson.toJson(arrayList);

Expected output: ["A","B","C"]
Actual output: null

What version of the product are you using? On what operating system?
gson v.2.2.3, tested on 2.2.4 as well
uname -a
Linux 3.11.0-15-generic #23-Ubuntu x86_64 GNU/Linux

This code is likely to be encountered in test classes, where inline 
initialization is most common and brevity is at the essence. Therefore, it 
would've been nice if it had worked.

Original issue reported on code.google.com by Michael....@gmail.com on 25 Jan 2014 at 1:16

GoogleCodeExporter commented 9 years ago
Probably has to do with the fact that this creates an anonymous class (which 
Gson barfs over).

A workaround is is to instead call it like this

gson.toJson(list, new TypeToken<List<String>>(){}.getType())

Not completely brief, but at least it avoids the bug.

Original comment by cog...@gmail.com on 6 Mar 2014 at 11:46

GoogleCodeExporter commented 9 years ago
Jackson has no problem serializing it without any additional parameters. :(

Original comment by adam.di...@gmail.com on 26 Mar 2014 at 10:52