2

我正在使用 NSJSONSerialization 解析推特搜索 api json 数据。要求是按标签搜索推文。在 Twitter api 控制台工具中,我正确获取了有关 15 条推文的数据。

书面代码是

if let results: NSDictionary = NSJSONSerialization .JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments  , error: errorPointer) as? NSDictionary {
             }

我得到的结果值为

{
    "search_metadata" =     {
        "completed_in" = "0.05";
        count = 15;
        "max_id" = 680240431771156480;
        "max_id_str" = 680240431771156480;
        "next_results" = "?max_id=680240407322689535&q=%23ChristmasEve&include_entities=1";
        query = "%23ChristmasEve";
        "refresh_url" = "?since_id=680240431771156480&q=%23ChristmasEve&include_entities=1";
        "since_id" = 0;
        "since_id_str" = 0;
    };
    statuses =     (
                {
            contributors = "<null>";
            coordinates = "<null>";
            "created_at" = "Fri Dec 25 04:15:31 +0000 2015";
            entities =             {
                hashtags =                 (
                                        {
                        indices =                         (
                            0,
                            13
                        );
                        text = ChristmasEve;
                    },
                                        {

这是不完整的。我什至尝试使用 SwiftyJSon 库,但我得到了类似的结果。

有没有办法在不使用任何外部库的情况下获取状态/推文信息值?

4

1 回答 1

1

鉴于您提到您收到多条推文 (15),您从 API 返回的 JSON 数据可能是一个数组,而不是字典。在进行网络调用时处理这两种情况是一个很好的做法:

    do {
        let object = try NSJSONSerialization.JSONObjectWithData(data, options: [])
        if let dictionary = object as? [NSObject: AnyObject] {
            // Handle dictionary
        } else if let array = object as? [[NSObject: AnyObject]] {
            // Handle array
        }

    } catch {

    }
于 2015-12-25T16:39:37.007 回答