在swift中使用嵌套的对象数组为json创建对象

时间:2016-11-22 22:42:59

标签: json swift object

我需要用嵌套的对象数组解析json,我一直试图理解它的结构。

下面的Json结构

{  
  "data":[  
  {  
     "name":"NYSC",
     "query":"NYSC",
     "tweet_volume":18478,
     "tweets_sata":[  
        {  
           "tweet":"RT @badt_BOI_: For every graduate going for youth service this Nov, make sure u take the Skill Acquisition Program in NYSC camp seriously,\u2026",
           "user":"STEEV"
        },
        {  
           "tweet":"RT @phoonke: Take enough passports to camp. NYSC will collect passports like they want to use you for blood money. \ud83d\ude12",
           "user":"EBI"
        },
        {  
           "tweet":"RT @de_s0_la: Nysc year that I was preping my nursery 2 class for exams\nI asked them animal sounds.\nMe: A cat meows & a dog___?\nWhole class\u2026",
           "user":"Miyaki"
        },
        {  
           "tweet":"RT @Hisroyaldopenez: When You see your ex that NYSC posted to Borno https:\/\/t.co\/BDUWwSdW4Y",
           "user":"Gbenga"
        },
        {  
           "tweet":"RT @OjokutuDaniel: If you're are from Kogi State (Kabba), studied Civil Engr (must have finished NYSC) there's a scholarship and job offer\u2026",
           "user":"Ad\u00e9r\u00f3j\u00fa"
        },
        {  
           "tweet":"RT @ThisIsKennys: Osas that had already made plans about how she will go to Abuja & buy iPhone 7 within 2months because politicians... NYSC\u2026",
           "user":"@i.wear.asika \u2702\ufe0f"
        },
        {  
           "tweet":"RT @hakorayday: Some of y'all ladies are just getting posted for NYSC & y'all be talking about wanting a man earning 200k. U will be OK wen\u2026",
           "user":"Jollof Rice"
        },
        {  
           "tweet":"RT @de_s0_la: Nysc year that I was preping my nursery 2 class for exams\nI asked them animal sounds.\nMe: A cat meows & a dog___?\nWhole class\u2026",
           "user":"Adebisi KingLY \ud83d\udc51"
        },
        {  
           "tweet":"RT @SlimDandyMUFC: People talking about NYSC everywhere but I can't relate cos school dropout https:\/\/t.co\/b2Bn0lU11l",
           "user":"@i.wear.asika \u2702\ufe0f"
        },
        {  
           "tweet":"RT @Svdia_: Who are those coming to Birnin Kebbi for NYSC??! Contact me for accommodation. RT please",
           "user":"Isah"
        },
        {  
           "tweet":"RT @VhickThorKING: After doing dry fasting expecting Nysc to post u to either Lagos or Port Harcourt & you magically end up in the North\ud83d\ude02\ud83d\ude2d\ud83d\ude2d\u2026",
           "user":"."
        },
        {  
           "tweet":"Nysc be breaking people's hearts.\ud83d\ude05\ud83d\ude04\ud83d\ude02",
           "user":"Password"
        },
        {  
           "tweet":"RT @I_pissVodka: Wearing NYSC Kaki to church isn't a bad idea...all na Service",
           "user":"Obie Drakes"
        },
        {  
           "tweet":"RT @Beardrain: If you can have sex in nysc camps, you can have sex inside a dustbin",
           "user":"Jollof Rice"
        },
        {  
           "tweet":"RT @Ms_DHK: People after checking their NYSC: https:\/\/t.co\/7W8IiOCcNY",
           "user":"."
        }
     ]
  }, 
  {  
     "name":"NYSC",
     "query":"NYSC",
     "tweet_volume":18478,
     "tweets_sata":[  
        {  
           "tweet":"RT @badt_BOI_: For every graduate going for youth service this Nov, make sure u take the Skill Acquisition Program in NYSC camp seriously,\u2026",
           "user":"STEEV"
        },
        {  
           "tweet":"RT @phoonke: Take enough passports to camp. NYSC will collect passports like they want to use you for blood money. \ud83d\ude12",
           "user":"EBI"
        },
        {  
           "tweet":"RT @de_s0_la: Nysc year that I was preping my nursery 2 class for exams\nI asked them animal sounds.\nMe: A cat meows & a dog___?\nWhole class\u2026",
           "user":"Miyaki"
        },
        {  
           "tweet":"RT @Hisroyaldopenez: When You see your ex that NYSC posted to Borno https:\/\/t.co\/BDUWwSdW4Y",
           "user":"Gbenga"
        },
        {  
           "tweet":"RT @OjokutuDaniel: If you're are from Kogi State (Kabba), studied Civil Engr (must have finished NYSC) there's a scholarship and job offer\u2026",
           "user":"Ad\u00e9r\u00f3j\u00fa"
        },
        {  
           "tweet":"RT @ThisIsKennys: Osas that had already made plans about how she will go to Abuja & buy iPhone 7 within 2months because politicians... NYSC\u2026",
           "user":"@i.wear.asika \u2702\ufe0f"
        },
        {  
           "tweet":"RT @hakorayday: Some of y'all ladies are just getting posted for NYSC & y'all be talking about wanting a man earning 200k. U will be OK wen\u2026",
           "user":"Jollof Rice"
        },
        {  
           "tweet":"RT @de_s0_la: Nysc year that I was preping my nursery 2 class for exams\nI asked them animal sounds.\nMe: A cat meows & a dog___?\nWhole class\u2026",
           "user":"Adebisi KingLY \ud83d\udc51"
        },
        {  
           "tweet":"RT @SlimDandyMUFC: People talking about NYSC everywhere but I can't relate cos school dropout https:\/\/t.co\/b2Bn0lU11l",
           "user":"@i.wear.asika \u2702\ufe0f"
        },
        {  
           "tweet":"RT @Svdia_: Who are those coming to Birnin Kebbi for NYSC??! Contact me for accommodation. RT please",
           "user":"Isah"
        },
        {  
           "tweet":"RT @VhickThorKING: After doing dry fasting expecting Nysc to post u to either Lagos or Port Harcourt & you magically end up in the North\ud83d\ude02\ud83d\ude2d\ud83d\ude2d\u2026",
           "user":"."
        },
        {  
           "tweet":"Nysc be breaking people's hearts.\ud83d\ude05\ud83d\ude04\ud83d\ude02",
           "user":"Password"
        },
        {  
           "tweet":"RT @I_pissVodka: Wearing NYSC Kaki to church isn't a bad idea...all na Service",
           "user":"Obie Drakes"
        },
        {  
           "tweet":"RT @Beardrain: If you can have sex in nysc camps, you can have sex inside a dustbin",
           "user":"Jollof Rice"
        },
        {  
           "tweet":"RT @Ms_DHK: People after checking their NYSC: https:\/\/t.co\/7W8IiOCcNY",
           "user":"."
        }
     ]
  }

这是我能够实现的,但我被困了

json的对象

class Trend: NSObject, JSONDecodable {

  var _name: String?
  var _query: String?
  var _tweet_volume: Int?
  var _tweets_sata: [TweetsSatum]?


required init(_ json: [String: Any]) {
    super.init()

    _name = json["name"] as? String
    _query = json["query"] as? String
    _tweet_volume = json["tweet_volume"] as? Int
    _tweets_sata = json["tweets_sata"] as?  [TweetsSatum]
}


class TweetsSatum: NSObject {
    var _tweet: String?
    var _user: String?

    required init(_ json: [String: Any]) {
      super.init()
     _tweet = json["tweet"] as? String
      _user = json["user"] as? String
   }

}

JSONDecode协议

 protocol JSONDecodable {
  init?(_ json: [String: Any])
}

1 个答案:

答案 0 :(得分:1)

没有自定义协议的简单解决方案 - 推文类可以限制为[String:String]

它为StringInt值使用提到的nil coalescing运算符,并为tweetsSata创建一个默认的空数组(命名遵循Swift约定,这不是javascript或PHP )。

此外 - 为了更好的可读性,不要忽略初始化器中的参数标签是有用的。

class Trend: NSObject {

    let name: String
    let query: String
    let tweetVolume: Int
    var tweetsSata = [TweetsSatum]()

    required init(json: [String: Any]) {
        name = json["name"] as? String ?? ""
        query = json["query"] as? String ?? ""
        tweetVolume = json["tweet_volume"] as? Int ?? 0
        if let tweets = json["tweets_sata"] as? [[String:String]] {
            tweetsSata = tweets.map { TweetsSatum(json:$0) }
        }
    }


    class TweetsSatum: NSObject {
        let tweet: String
        let user: String

        required init(json: [String: String]) {
            tweet = json["tweet"] ?? ""
            user = json["user"] ?? ""
        }
    }
}

考虑使用结构而不是继承自NSObject的类,除非您确实需要符合NSObject协议。

相关问题