Search code examples
iosswift4nsobjectswifty-json

How to initialize multiple dictionary in json in 1 NSObject using SwiftyJson


My API response is look like this

{
"error": false,
"id": "6",
"user_id": 7,
"users": [
    {
        "user_id": 1,
        "username": "spiderman"
    },
    {
        "user_id": 7,
        "username": "wonderwoman"
    }
    ],
"info": [
    {
        "id": 471,
        "message": "abc",
        "age": 10,
    }
    ]
}

I know how to initialize the value of id,user_id and error in NSOject. But I dont know how can I initialize the array of users and info in the same NSObject class.

Now I initialize the JSON like this

import UIKit
import SwiftyJSON

class MyItem: NSObject {

    var userId : Int
    var error : Bool 
    var id : Int 

    init?(dict: [String :JSON]) {
        self.id = dict["id"]?.int ?? 0
        self.error = dict["error"]?.bool ?? false
        self.userId = dict["userId"]?.int ?? 0
    }
}

Now the problem is I don't know how to initialize data inside the users and info dictionary.How should I arrange it and how can I use it in other class

Kindly give an example.


Solution

  • The best way to do this is to create 2 different classes for user and info as follows:

    class MyItem : NSObject {
    
        var error : Bool!
        var id : String!
        var info : [Info]!
        var userId : Int!
        var users : [User]!
    
        init(fromJson json: JSON!){
            if json == nil{
                return
            }
            error = json["error"].boolValue
            id = json["id"].stringValue
            info = [Info]()
            let infoArray = json["info"].arrayValue
            for infoJson in infoArray{
                let value = Info(fromJson: infoJson)
                info.append(value)
            }
            userId = json["user_id"].intValue
            users = [User]()
            let usersArray = json["users"].arrayValue
            for usersJson in usersArray{
                let value = User(fromJson: usersJson)
                users.append(value)
            }
        }
    }
    
    class User : NSObject {
    
        var userId : Int!
        var username : String!
    
    
        init(fromJson json: JSON!){
            if json == nil{
                return
            }
            userId = json["user_id"].intValue
            username = json["username"].stringValue
        }
    }
    
    class Info : NSObject {
    
    var age : Int!
    var id : Int!
    var message : String!
    
    init(fromJson json: JSON!){
        if json == nil{
            return
        }
        age = json["age"].intValue
        id = json["id"].intValue
        message = json["message"].stringValue
    }
    }
    

    By doing this you would be able to directly access the value of user and info like for eg: MyItem.users[index].userId