2016-09-06 145 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