SimpiMind SimpiMind - 17 days ago 4
JSON Question

Creating objects for json with nested array of object in swift

I need to parse a json with a nested array of objects, i have been stucked trying to understand how its structured.

Json structure below

{
"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":"."
}
]
}


This is what i have been able to achieve, but i am stucked

Objects for the 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

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

Answer

Simple solution without your custom protocol – the tweet class can be constrained to [String:String].

It uses the mentioned nil coalescing operator for the String and Int values and creates a default empty array for tweetsSata (the naming follows the Swift convention, this is not javascript or PHP).

Further – for better readability – it's useful not to ignore the parameter label in the initializers.

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"] ?? ""
        }
    }
}

Consider to use structs rather than classes inherited from NSObject unless you really need conformance to the NSObject protocol.