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