【发布时间】:2016-07-21 20:26:45
【问题描述】:
我正在尝试使用 Delphi XE7 解析来自 Twitter API 的 JSON 结果。我收到“Invalid class typecast”错误,但我使用在线验证器检查 JSON 并没有问题。
这是 JSON 结果:
[
{
"trends":
[
{
"name":"#OneDirectionIsOverParty",
"url":"http://twitter.com/search?q=%23OneDirectionIsOverParty",
"promoted_content":null,
"query":"%23OneDirectionIsOverParty",
"tweet_volume":410022
},
{
"name":"#TheDarkKnight",
"url":"http://twitter.com/search?q=%23TheDarkKnight",
"promoted_content":null,
"query":"%23TheDarkKnight",
"tweet_volume":null
},
{
"name":"#QuintaComOClubeSdv",
"url":"http://twitter.com/search?q=%23QuintaComOClubeSdv",
"promoted_content":null,
"query":"%23QuintaComOClubeSdv",
"tweet_volume":23756
}
],
"as_of":"2016-07-21T20:14:13Z",
"created_at":"2016-07-21T20:08:31Z",
"locations":
[
{
"name":"Worldwide",
"woeid":1
}
]
}
]
这是我的解析函数:
procedure ParseJSON(const JSON: string);
var
JSONObject: TJSONObject;
MessageText: TJSONArray;
NodeDetails: TJSONObject;
MsgDetail: TJSONString;
I: Integer;
Item: TListItem;
begin
JSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(JSON), 0) as TJSONObject;
MessageText := JSONObject.Get('trends').JSONValue as TJSONArray;
for I := 0 to TJSONArray(MessageText).Size - 1 do
begin
Item := Form1.ListView1.Items.Add;
NodeDetails := MessageText.Get(I) as TJSONObject;
MsgDetail := NodeDetails.Get('query').JSONValue as TJSONString;
Item.Caption := MsgDetail.Value;
end;
实际上,此函数适用于来自 Twitter API 的其他 JSON 结果。它不仅对这一个结果起作用。
【问题讨论】:
-
调试器在哪一行中断?你已经通过代码了吗?
-
嘿@JerryDodge "JSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(JSON), 0) as TJSONObject;"
-
我不熟悉这个特定的 JSON 库,但我猜你应该将它解析为数组而不是对象 - 因为根元素是一个数组。事实上,您的代码似乎与此 JSON 数据完全不匹配。
-
另外,代码泄露了
ParseJSONValue()返回的TJSONValue。使用完毕后需要Free。
标签: json delphi parsing delphi-xe7