swift - 使用 NSJSONSerialization 解析 twitter 搜索 json 数据

标签 swift parsing twitter swifty-json twitter-rest-api

我正在使用 NSJSONSerialization 解析 twiter search 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 库,但我得到了类似的结果。

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

最佳答案

鉴于您提到您收到多条推文 (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 {

    }

关于swift - 使用 NSJSONSerialization 解析 twitter 搜索 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34460287/

相关文章:

java - 当我尝试使用 BufferedReader 将整数输入存储到数组中时遇到数字格式异常

datetime - 在 Hive 中转换日期格式

php - Cronjob 但适用于 jQuery/Javascript

ios - 无法在 Swift for 循环中更改核心数据属性

ios - iOS TestFlight版本更新为AppStore版本

Python解析csv文件——用冒号代替逗号

php - 搜索查询,例如 Twitter 热门话题

ios - 尝试将 AlamoFire JSON 响应映射到类并接收 "Fatal Error: Unexpectedly found nil while unwrapping optional"

ios - Swift 3 - 将 bool 值发送到不同的类

在 Parsing Expressive Grammar (PEG.js) 中解析保留字