Why this does not work?
public static class MyBean extends HashMap<String, String> {
public String city;
}
/**
* @param args
*/
public static void main(String[] args) {
MyBean bean = new MyBean();
bean.city = "some city";
Gson gson = new Gson();
String json = gson.toJson(bean);
System.out.println(json);
}
Why I dont see city value in json?
That’s because instances implementing
Maphave special treatment by Gson. By default only its entry set will be serialized. You need to create a custom serializer which serializes both the entryset and the bean properties of interest separately.E.g.
Which can be used as follows:
Update: hmm, as per the comment on the question (you should actually have posted it on the answer so that I will be notified immediately), the
context.serialize(myBean.entrySet())didn’t seem to work out. And you’re right, I just did a local test and I got the same exception. I tried adding aTypeTokenonSet<Entry<String, String>>, but that ends up with an empty entryset somehow. Wrapping it in another map did work for me. I’ve updated the line in the answer.