【问题标题】:parsing twitter search json data using NSJSONSerialization使用 NSJSONSerialization 解析 twitter 搜索 json 数据
【发布时间】:2015-12-25 05:34:50
【问题描述】:

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

有什么方法可以在不使用任何外部库的情况下获取状态/推文信息值?

【问题讨论】:

  • 不确定您的问题是什么,但我怀疑 Twitter 的响应不是字典,而是数组。

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


【解决方案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 {

    }

【讨论】:

  • 但是在代码中我得到了不完整的数据值
猜你喜欢
  • 2013-01-19
  • 2012-12-20
  • 2012-08-28
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多