0

I am using gson.toJson to convert my java objects to JSON and I have an issue with a particular structure.

Here is what my code looks like:

  user_info.setUser_data(Arrays.asList(new HashMap<String, String>() {{
            put("x", "y");
            put("x1", "y2");
        }}, new HashMap<String, String>() {{
            put("x", "y");
            put("x1", "y2");
        }}));
  user_info.setUser_data2(new HashMap<String, Object>() {{
            put("x", 5);
        }}); 

Where user_data element is written as follows: (user_data2 is set in the following manner)

    private List<?> user_data= new ArrayList<>();

    public List<?> getUser_data() {
        return user_data;
    }

 public void setUser_data(List<?> user_data) {
        this.user_data = user_data;
    }

But after using gson.toJson I am getting the following empty result for user_data while user_data2 is not even bein converted.

  "user_data":[
         null,
         null
      ]
   }

What I expect to get is :

"user_data": [
        {
            "x": "y",
            "x1": "y2"
        },
        {
            "x": "y",
            "x1": "y2"
        }
    ],
    "user_data2": {
        "x": 5
    }
}

What am I getting wrong here?

PloniStacker
  • 574
  • 4
  • 23
  • 1
    1) Don't use double-brace initializers. It's just an anti-pattern with several drawbacks (creates extra classes that may hold references to outer classes): https://stackoverflow.com/questions/55118740/how-to-use-double-brace-initialization-for-map-of-map . 2) Gson does not _really_ support anonymous class serialization because of being unable to deserialize them properly (because of the outer class reference). Here is a very old issue for that: https://github.com/google/gson/issues/298 – terrorrussia-keeps-killing Jan 20 '21 at 10:01
  • 1
    3) Note that Gson _may_ serialize such objects in some cases, but I suspect you have declared your `user_data` as `List` or something like that. Making it declared as `List>` makes it work (clearly, Gson uses type hints then), however I would strongly suggest you declare types as concrete as possible (use at least interfaces with proper parameterization), and never use non-static anonymous classes (Note that Gson is not the only tool being unable to do that). – terrorrussia-keeps-killing Jan 20 '21 at 10:04
  • Thanks @fluffy! I concretified everything and it works. – PloniStacker Jan 20 '21 at 14:38

0 Answers0