Json Gson不工作(异常对象/字符串)

时间:2012-08-30 15:11:02

标签: java json gson

我有将JSON转移到java类型的问题,我想传输这个JSON:

{ "kind": "fusiontables#sqlresponse", "columns": [  "Pre",  "Post" ], "rows": [  [   "Si2",   "Si2"  ],  [   "CeSP-A",   "CeSP-A"  ],  [   "Si2",   "Si1"  ],  [   "Si1",   "Si2"  ],  [   "Si2",   "Si1"  ],  [   "Si1",   "Si2"  ] ]}

到一个java列表,其中每个列表都有两个私有字符串Pre和Post

这是我的代码:

Gson gson = new Gson();
        List<Edges> list = gson.fromJson(jsonU,
                new TypeToken<List<Edges>>() {
                }.getType());
        for (int i = 0; i < list.size(); i++) {
            Edges p = list.get(i);
            System.out.println(p.getPre() + ", " + p.getPost());
            System.out.println();
        }

和 jsonU是JSON文件的字符串

{ "kind": "fusiontables#sqlresponse", "columns": [  "Pre",  "Post" ], "rows": [  [   "Si2",   "Si2"  ],  [   "CeSP-A",   "CeSP-A"  ],  [   "Si2",   "Si1"  ],  [   "Si1",   "Si2"  ],  [   "Si2",   "Si1"  ],  [   "Si1",   "Si2"  ] ]}

然而,我收到了错误:

 Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
你可以帮我解决这个问题吗?非常感谢你

1 个答案:

答案 0 :(得分:0)

您告诉GSON反序列化List<Edges>您传递的JSON以对象开头,并带有{}令牌。

GSON,根据您传递给它的类型参数,期望类似于:

[
    { "kind": .... },
    { "kind: .... },
    ...
]

换句话说,当你传递对应于单个对象的JSON时,GSON如何构造一个List的东西?