如何过滤 json swift 中的内容

How to filter content in json swift

我的应用程序中有一个包含各种类别的侧边菜单,例如:"all posts, international, national etc"。现在我从 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 数据,并仅加载属于我的 table 视图中相应侧边菜单条目的数据。

您只需在将 'new' 成员添加到数组之前检查 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)
    }
}