简体   繁体   English

如何使用GSON将地图映射转换为JSON,然后又转换为JSON?

[英]How do I convert a Map of Maps into JSON, and back, using GSON?

I've got a Map<Integer, Map<Class<?>, Serializable>> that I'm trying to store as a JSON string. 我有一个Map<Integer, Map<Class<?>, Serializable>> ,我想将它存储为JSON字符串。 Then, later, I'm trying to read from that same JSON formatted String to recreate the object. 然后,稍后,我尝试从相同的JSON格式的String中读取内容以重新创建对象。 How would you do this using GSON? 您将如何使用GSON做到这一点?

Rather then using Map of Map try to use class structure. 而不是然后使用Map尝试使用Map的类结构。

Or you can use following library to achieve the same. 或者,您可以使用以下库来实现相同目的。

com.google.gson.Gson.Gson()

use following method : 使用以下方法:

public static String getJSONString(Object jsonObject)
{
    if(jsonObject == null) return "";
    return new Gson().toJson(jsonObject);
}

You will not have any issue at all when trying to serialize Map<Integer, Map<Class<?>, Serializable>> , the problem is when trying to deserialize the JSON back. 尝试序列化Map<Integer, Map<Class<?>, Serializable>> ,您根本不会有任何问题,问题在于尝试反序列化JSON时。 I guess you can write your own deserializer for the Class<?> depending on what you actually need, but deserializing Serializable is not possible. 我猜您可以根据实际需要为Class<?>编写自己的反序列Serializable器,但是反Serializable是不可能的。

Serializable is not a concrete class, it is an interface. Serializable不是具体的类,它是一个接口。 You can't instantiate a Serializable , you can only instantiate a concrete class that implements Serializable . 您无法实例化Serializable ,只能实例化实现Serializable的具体类。 Sure you can write you own custom serializer/deserializer for Serializable by including the concrete class information inside the serialized JSON, but then you need to include all possible classes which implements Serializable , which is not realistic at all. 当然,您可以通过在序列化的JSON中包含具体的类信息来编写自己的自定义序列化器/反Serializable化器,以实现Serializable ,但是随后您需要包括实现Serializable所有可能的类,这根本是不现实的。

Reference: https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types 参考: https : //sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM