JamesDeCarlo / google-gson

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

Double brace initialization not working #346

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Map<String, List<String>> jsonData = new HashMap<String, List<String>>();
jsonData.put("test", new ArrayList<String>() {
    {
        add("1");
        add("2");
        add("3");
    }
});
System.out.println(new Gson().toJson(jsonData));
//OUTPUT = {}

Map<String, List<String>> jsonData = new HashMap<String, List<String>>();
ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
jsonData.put("test", list);
System.out.println(new Gson().toJson(jsonData));

//OUTPUT = {"test":["1","2","3"]}

Original issue reported on code.google.com by neyas...@gmail.com on 13 Jul 2011 at 9:39

GoogleCodeExporter commented 9 years ago
The fundamental problem is that you aren't supplying GSON with enough type 
information and so it has to infer the type from the value. You can work-around 
this by providing the type in your call to toJson():

  String json = gson.toJson(jsonData, new TypeToken<Map<String, List<String>>>() {}.getType()));

We still have a problem where GSON never serializes anonymous classes, which is 
an unfortunate policy in this instance.

Original comment by limpbizkit on 1 Oct 2011 at 4:40

GoogleCodeExporter commented 9 years ago

Original comment by limpbizkit on 2 Oct 2011 at 3:38

GoogleCodeExporter commented 9 years ago
Issue 370 has been merged into this issue.

Original comment by limpbizkit on 19 Oct 2011 at 4:30