开发者

serialize json object which extends map

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 Map have 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.

public class MyBeanSerializer implements JsonSerializer<MyBean> {

    @Override
    public JsonElement serialize(MyBean myBean, Type type, JsonSerializationContext context) {
        JsonObject object = new JsonObject();
        object.add("map", context.serialize(new HashMap<String, String>(myBean)));
        object.add("city", context.serialize(myBean.city));
        return object;
    }

}

Which can be used as follows:

Gson gson = new GsonBuilder().registerTypeAdapter(MyBean.class, new MyBeanSerializer()).create();
String json = gson.toJson(bean);
System.out.println(json);

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 a TypeToken on Set<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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜