2016-09-06 129 views
0

我正在尋找將JSON解序列化爲其POJO實例的幫助。頂級POJO Graph.java具有類型HashMap的屬性。雖然序列化它拋出使用Gson反序列化JSON

預計BEGIN_ARRAY但BEGIN_OBJECT在行ňNN路徑 $ .degreesCountMap [0]

我確切地知道這意味着什麼,以及如何解決它的對於頂級集合,但不知道如何爲另一個對象的屬性指定Type。

我做了這樣的問題,在這方面和許多其他論壇審查討論,但我實在不明白的答案,可以幫助我。

我將不勝感激任何幫助。

這裏是圖的JSON:

{ 
    "nodeCount":3, 
    "edgeCount":2, 
    "degreesCountMap":[ 
     { 
     "ONE":2 
     }, 
     { 
     "TWO":1 
     } 
    ], 
    "nodes":[ 
     { 
     "index":0, 
     "connectedIndices":[ 
      1 
     ] 
     }, 
     { 
     "index":1, 
     "connectedIndices":[ 
      0, 
      2 
     ] 
     }, 
     { 
     "index":2, 
     "connectedIndices":[ 
      1 
     ] 
     } 
    ] 
} 

這裏是POJO的

Graph.java

public class Graph { 
    private HashMap<Degree, Integer> degreesCountMap; 

    private Integer edgeCount; 
    private Integer nodeCount; 
    private ArrayList<Node> nodes; 
    public HashMap<Degree, Integer> getDegreesCountMap() { 
     return degreesCountMap; 
    } 

    public void setDegreesCountMap(HashMap<Degree, Integer> degreesCountMap) { 
     this.degreesCountMap = degreesCountMap; 
    } 

    public void setNodes(ArrayList<Node> nodes) { 
     this.nodes = nodes; 
    } 
} 

Degree.java

public enum Degree { 
    ZERO, ONE, THREE, FOUR; 
} 

Node.java

public class Node { 

    private ArrayList<Integer> connectedIndices; 
    private int index; 

    public ArrayList<Integer> getConnectedIndices() { 
     return connectedIndices; 
    } 

    public int getIndex() { 
     return index; 
    } 

    public void setConnectedIndices(ArrayList<Integer> connectedIndices) { 
     this.connectedIndices = connectedIndices; 
    } 

    public void setIndex(int index) { 
     this.index = index; 
    } 
} 

GraphTest.java

@Test 
public void testJsonToGraph() { 

    String json = "{\"nodeCount\":3,\"edgeCount\":2," 
      + "\"degreesCountMap\":[{\"ONE\":2},{\"TWO\":1}],"// <--to fail 
      + "\"nodes\":[{\"index\":0,\"connectedIndices\":[1]}," 
      + "{\"index\":1,\"connectedIndices\":[0,2]}," 
      + "{\"index\":2,\"connectedIndices\":[1]}]}"; 

    try { 
     graph = gson.fromJson(json, Graph.class); 
     assertNotNull(graph); 
    } catch (Exception e) { // Intentionally capturing to diagnose 
     e.printStackTrace(); 
    } 
} 

回答

1

的問題是,您發佈的JSON是無效的。

因爲地圖可用於任何對象映射到任何物體GSON必須使地圖作爲陣列的兩個對象。

在地圖對象的有效的JSON會是這樣的:

"degreesCountMap": [ 
    [ 
    "ONE", 
    2 
    ], 
    [ 
    "TWO", 
    1 
    ] 
] 

但因爲使用的是枚舉作爲鍵下面的代碼是有效的:

"degreesCountMap": { 
    "TWO": 1, 
    "ONE": 2 
} 

解決方案:編輯您的json有效。另外,我認爲你的學位enum中缺少TWO

注意:因爲您使用枚舉有剛"ONE"但如果你使用的典型對象的關鍵它可能看起來像這樣:

"degreesCountMap": [ 
    [ 
    { "degree": "ONE" }, 
    2 
    ], 
    [ 
    { "degree": "TWO" }, 
    1 
    ] 
] 
+0

謝謝 「degreesCountMap」:{ 「二」: 1, 「ONE」:2 }行之有效 –

+0

請接受這個答案,如果你覺得有用,所以它不會被視爲沒有解決,兌現我的工作。謝謝。 – pr0gramist