Json Parse"无效类类型转换"问题.[Delphi XE7]

Max*_*ane 1 delphi parsing json delphi-xe7

我试图使用Delphi XE7从Twitter API解析JSON结果.我收到"无效的类类型转换"错误,但我使用在线验证程序检查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
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

这是我的解析功能:

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;
Run Code Online (Sandbox Code Playgroud)

实际上,此函数适用于Twitter API的其他JSON结果.它不仅仅针对这一结果.

Dav*_*nan 6

JSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(JSON), 0) as TJSONObject;
Run Code Online (Sandbox Code Playgroud)

JSON的根是一个数组,而不是一个对象.因此错误.

您需要将返回值转换为ParseJSONValue()to TJSONArray而不是TJSONObject,然后您可以访问数组中的第一个元素并读取其trends值.您已经拥有解析数组的代码,因此您清楚地知道如何执行此操作.

如果您不清楚对象和数组的JSON术语,请阅读JSON规范.

  • 由于相同的代码用于解析Twitter的多个结果,其中一些以*object*开头,一些以*array*开头,因此可以将`ParseJSONValue()`的返回值保存到本地`TJSONValue`变量然后在转换之前使用`is`运算符检查它是否真的是一个`TJSONObject`或`TJSONArray`. (2认同)