2016-04-26 154 views
0

,我有以下代碼示例什麼,我想實現:的Java GSON序列化和內部HashMap的反序列化對象(鍵,對象)

public static void main(String args[]) { 

    Map<String, Object> map = new HashMap<String, Object>(); 
    map.put("1", new A()); 
    map.put("2", new B()); 
    String json = new Gson().toJson(map); 
    Type type = new TypeToken<Map<String, Object>>(){}.getType(); 
    map = new Gson().fromJson(json, type); 
    A a = (A) map.get("1"); 
    B b = (B) map.get("2"); 

} 

static class A { 

    int inum = 1; 
    double dnum = 1.0; 
    String str = "1"; 

} 

static class B { 

    int inum = 2; 
    double dnum = 2.0; 
    String str = "2"; 

} 

下面的代碼導致此異常:

Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to ParseJson$A 
    at ParseJson.main(ParseJson.java:19) 

所以問題是: 如何獲得Gson序列化和反序列化的泛型HashMap中的正確實例?

+0

使用一個類型令牌。將副本應用於「Map」而不是「List」。 – Savior

+1

'Type type = new TypeToken (){}。getType();'缺少'>'。 – totoro

+0

謝謝。糾正了這個問題。 – Nom1fan

回答

2

Object被反序列化爲com.google.gson.internal.LinkedTreeMap,所以告訴Gson你需要A類。

public static void main(String args[]) { 
    Map<String, Object> map = new HashMap<>(); 
    map.put("1", new A()); 
    String json = new Gson().toJson(map); 
    Type type = new TypeToken<Map<String, A>>() { 
    }.getType(); 
    map = new Gson().fromJson(json, type); 
    A a = (A) map.get("1"); 
    System.out.println(a.str); 
} 

static class A { 
    private int num1 = 1; 
    private double num2 = 2.0; 
    private String str = "String"; 
} 

希望它有幫助。

UPDATE

甲基類(X在這種情況下)可能是一個解決方案:

public static void main(String args[]) { 
    Map<String, Object> map = new HashMap<String, Object>(); 
    map.put("1", new A()); 
    map.put("2", new B()); 
    String json = new Gson().toJson(map); 
    Type type = new TypeToken<Map<String, X>>(){}.getType(); 
    map = new Gson().fromJson(json, type); 
    X a = (X) map.get("1"); 
    X b = (X) map.get("2"); 
    System.out.println(a.str); 
    System.out.println(b.str); 
} 

static class X { 
    int inum; 
    double dnum; 
    String str; 

    X() { 
    } 
} 

static class A extends X { 
    A() { 
     inum = 1; 
     dnum = 1.0; 
     str = "1"; 
    } 
} 

static class B extends X { 
    B() { 
     inum = 2; 
     dnum = 2.0; 
     str = "2"; 
    } 
} 
+0

你的回答是正確的,但我實際上試圖實現一些更復雜的東西。我更新了問題主體來說明。我用Object來定義HashMap是有原因的。因爲我需要包含不同的類型。謝謝! – Nom1fan

+0

看來我再次簡化了我的案例:)雖然你的回答在我給出的情況下再次正確。 在我真實的情況下,類之間沒有真正的相似性(可以只是字符串,枚舉或任何其他類。) 但我開始認爲沒有優雅的解決方案。我現在正在做的只是使用valueOf作爲變量,將其解釋爲原始的可視類型。但是對於複雜的課程,我沒有解決方案,所以我只是將他們的領域分開並分別傳給他們...... – Nom1fan