使用Gson对JSON进行反序列化

时间:2016-09-06 18:40:17

标签: json enums hashmap gson

我正在寻找帮助将JSON反序列化为其POJO的实例。顶级POJO Graph.java具有HashMap类型的属性。序列化时抛出

  

预期BEGIN_ARRAY但是在行 n nn 路径下是BEGIN_OBJECT   $ .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 个答案:

答案 0 :(得分:1)

问题是您发布的JSON无效。

因为Map可用于将任何对象映射到任何对象,Gson必须将map作为包含两个对象的数组。

地图对象的有效JSON如下所示:

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

但由于您使用枚举作为键,因此以下代码也有效:

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

解决方案:将您的json编辑为有效的json。此外,我认为您在学位课程中缺少TWO

注意:因为你使用enum只有"ONE",但是如果你使用一个典型的对象作为一个键,它可能是这样的:

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