Hashmap的Gson序列化

时间:2018-09-17 19:01:23

标签: java serialization gson

我有一个哈希图的哈希图,该哈希图需要序列化(Map ),目前仅处理Strings。 当前使用gson对其进行序列化。

{cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58 = {tz:“ eeee” dis:“ aaaa” geoAddr:“ cccc,dddd” id:@ cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58 geoState:“ dddd”区域:1000ft²geoCity:“ cccc” bbbb}}

Gson gson = new GsonBuilder().create();
String string = gson.toJson(map);

但是似乎通过添加以下中间键值对和哈希码来改变整体结构。

{“ cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58”:{“ map”:{“ tz”:{“ val”:“ eeee”},“ dis”:{“ val”:“ aaaa”}, “ geoAddr”:{“ val”:“ cccc,dddd”},“ id”:{“ val”:“ cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58”},“ geoState”:{“ val”:“ dddd” },“ area”:{“ val”:1000.0,“ unit”:“ft²”},“ geoCity”:{“ val”:“ cccc”},“ bbbb”:{}},“ hashCode”:0} }

将其反序列化回Map时,最终会得到额外的键值对。

Gson gson = new Gson();
Type listType = new TypeToken<Map<String, Map>>()
{
}.getType();
map = gson.fromJson(string, listType); 

{cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58 = {map = {tz = {val = eeee},dis = {val = aaaa},geoAddr = {val = cccc,dddd},id = {val = cb9b4b3d -8d2e-41b2-9a21-1657dbd14f58},geoState = {val = dddd},area = {val = 1000.0,unit =ft²},geoCity = {val = cccc},bbbb = {}},hashCode = 0.0}} < / p>

有没有一种方法可以反序列化为原来的结构。我使用的第三方库不了解此反序列化的Map。

1 个答案:

答案 0 :(得分:1)

这对我有用(gson 2.8):

public static void main(String[] args) {
    String json = "{"
        + "  \"cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58\": {"
        + "    \"tz\": \"eeee\","
        + "    \"dis\": \"aaaa\","
        + "    \"geoAddr\": \"cccc\","
        + "    \"id\": \"cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58\","
        + "    \"geoState\": \"dddd\","
        + "    \"area\": 1000,"
        + "    \"geoCity\": \"cccc\""
        + "  }"
        + "}";

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    Map<String, Map<String, Object>> map = gson.fromJson(json, new TypeToken<Map<String, Map<String, Object>>>(){}.getType());
    System.out.println("Map.toString() is:");
    System.out.println(map);
    String serialisedMap = gson.toJson(map);
    System.out.println("Map to json is:");
    System.out.println(serialisedMap);
}

打印:

Map.toString() is:
{cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58={tz=eeee, dis=aaaa, geoAddr=cccc, id=cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58, geoState=dddd, area=1000.0, geoCity=cccc}}
Map to json is:
{
  "cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58": {
    "tz": "eeee",
    "dis": "aaaa",
    "geoAddr": "cccc",
    "id": "cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58",
    "geoState": "dddd",
    "area": 1000.0,
    "geoCity": "cccc"
  }
}