0

我有一个将 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

你能帮我解决这个问题吗?非常感谢

4

1 回答 1

0

您正在告诉 GSON 反序列化 aList<Edges>但您传递的 JSON 以对象开头,带有{}标记。

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

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

换句话说,当您传递对应于单个对象的 JSON 时,GSON 如何构造一个列表?

于 2012-08-30T15:14:18.597 回答