2016-11-22 5 views
-1

Мне нужно разобрать json с вложенным массивом объектов, я застрял, пытаясь понять, как он структурирован.Создание объектов для json с вложенным массивом объекта в swift

структура 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":"." 
     } 
    ] 
    } 

Это то, что я был в состоянии достичь, но я stucked

Объекты для 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]) 
} 
+0

Вы должны прочитать о нитном коалесцирующем операторе. 'if _query == nil { _query =" " } return _query' становится просто' return _query ?? "" – Alexander

+0

Нет, это не библиотека, ее протокол, который я объявил, позвольте мне добавить его ниже сообщения – SimpiMind

ответ

1

Простое решение без пользовательского протокола - класс твит может быть ограничен в [String:String].

Он использует упомянутый нулевой сливающихся оператора для значений String и Int и создает по умолчанию пустого массива для 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.

Смежные вопросы