【问题标题】:How to filter content in json swift如何在json swift中过滤内容
【发布时间】:2015-10-20 13:50:37
【问题描述】:

我的应用中有一个包含各种类别的侧菜单,例如:“所有帖子、国际、国内等”。现在我从 API 接收数据并使用 JSON 解析它。此数据存储在NSDictionary

代码如下:

import Foundation

class Member
{
    let imageName: NSData!
    let name: String?
    let about: String?
    let tag : String?

    init(dictionary:NSDictionary)
    {
        let url = dictionary["imageUrl"] as? String
        let imgdata = NSURL(string: url!)
        imageName = NSData(contentsOfURL: imgdata!)
        name = dictionary["title"] as? String
        tag = dictionary["TAG"] as? String
        // fixup the about text to add newlines
        let unescapedAbout = dictionary["postBody"] as? String
        about = unescapedAbout?.stringByReplacingOccurrencesOfString("\\n", withString:"\n", options:[], range:nil)
    }

    class func loadMembersFromFile(path: NSURL) -> [Member]
    {
        var members:[Member] = []
        if let data = NSData(contentsOfURL: path),
        //  if let data = NSData(contentsOfFile: path, options:[]),
            json = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)as? NSDictionary,
            team = json["items"] as? [NSDictionary]{
                for memberDictionary in team {
                    let member = Member(dictionary: memberDictionary)
                    members.append(member)
                }
        }
        return members
    }
}

现在 JSON 文件包含 TAG="international"、TAG="national" 等字段。

我想根据上面的标签过滤这个JSON数据,只加载属于我的表格视图中相应侧边菜单条目的数据。

【问题讨论】:

  • members.append(member) 之前检查member.tag

标签: ios json swift swift2 swift2.1


【解决方案1】:

您只需在将“新”成员附加到数组之前检查 TAG 的值

for memberDictionary in team {
    let member = Member(dictionary: memberDictionary)
    guard let tag = member.tag as? String else {
        continue 
    }
    if tag == theTag {  // Add a parameter 'theTag' (String) to your method
        members.append(member)
    }
}

【讨论】:

    猜你喜欢
    • 2013-07-14
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 2015-04-21
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多