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();
}
}
謝謝 「degreesCountMap」:{ 「二」: 1, 「ONE」:2 }行之有效 –
請接受這個答案,如果你覺得有用,所以它不會被視爲沒有解決,兌現我的工作。謝謝。 – pr0gramist