2

I have created model class for the user as below.

public class SignUpUser {
    public var fullName : String?
    public var id : Int?
    public var city : String?
    public var email : String?
    public var address : String?
    public var lastName : String?
    public var countryCode : String?
    public var firstName : String?
    public var zipCode : Int?
    public var contactNumber : Int?
    public var sex : String?
    public var dob : String?
    public var signupType : String?
    public var verified : String?
    public var emailTokenExpiration : String?
    public var updatedAt : String?
    public var createdAt : String?

/**
    Returns an array of models based on given dictionary.

    Sample usage:
    let user_list = User.modelsFromDictionaryArray(someDictionaryArrayFromJSON)

    - parameter array:  NSArray from JSON dictionary.

    - returns: Array of User Instances.
*/
    public class func modelsFromDictionaryArray(array:NSArray) -> [SignUpUser]
    {
        var models:[SignUpUser] = []
        for item in array
        {
            models.append(SignUpUser(dictionary: item as! NSDictionary)!)
        }
        return models
    }

/**
    Constructs the object based on the given dictionary.

    Sample usage:
    let user = User(someDictionaryFromJSON)

    - parameter dictionary:  NSDictionary from JSON.

    - returns: User Instance.

*/

    init?() {}


    required public init?(dictionary: NSDictionary) {
        fullName = dictionary["fullName"] as? String
        id = dictionary["id"] as? Int
        city = dictionary["city"] as? String
        email = dictionary["email"] as? String
        address = dictionary["address"] as? String
        lastName = dictionary["lastName"] as? String
        countryCode = dictionary["countryCode"] as? String
        firstName = dictionary["firstName"] as? String
        zipCode = dictionary["zipCode"] as? Int
        contactNumber = dictionary["contactNumber"] as? Int
        sex = dictionary["sex"] as? String
        dob = dictionary["dob"] as? String
        signupType = dictionary["signupType"] as? String
        verified = dictionary["verified"] as? String
        emailTokenExpiration = dictionary["emailTokenExpiration"] as? String
        updatedAt = dictionary["updatedAt"] as? String
        createdAt = dictionary["createdAt"] as? String
    }


/**
    Returns the dictionary representation for the current instance.

    - returns: NSDictionary.
*/
    public func dictionaryRepresentation() -> NSDictionary {

        let dictionary = NSMutableDictionary()

        dictionary.setValue(self.fullName, forKey: "fullName")
        dictionary.setValue(self.id, forKey: "id")
        dictionary.setValue(self.city, forKey: "city")
        dictionary.setValue(self.email, forKey: "email")
        dictionary.setValue(self.address, forKey: "address")
        dictionary.setValue(self.lastName, forKey: "lastName")
        dictionary.setValue(self.countryCode, forKey: "countryCode")
        dictionary.setValue(self.firstName, forKey: "firstName")
        dictionary.setValue(self.zipCode, forKey: "zipCode")
        dictionary.setValue(self.contactNumber, forKey: "contactNumber")
        dictionary.setValue(self.sex, forKey: "sex")
        dictionary.setValue(self.dob, forKey: "dob")
        dictionary.setValue(self.signupType, forKey: "signupType")
        dictionary.setValue(self.verified, forKey: "verified")
        dictionary.setValue(self.emailTokenExpiration, forKey: "emailTokenExpiration")
        dictionary.setValue(self.updatedAt, forKey: "updatedAt")
        dictionary.setValue(self.createdAt, forKey: "createdAt")

        return dictionary
    }

}

I am trying to conver the object to JSON with following way but getting error saying "invalid top-level type in json write"

let signUpuser =  SignUpUser()
        signUpuser?.fullName = "Teswt"
        signUpuser?.id = 1
        signUpuser?.city = "Test"
        signUpuser?.email = "Test"
        signUpuser?.address = "Test"
        signUpuser?.lastName = "Test"
        signUpuser?.countryCode = "Test"
        signUpuser?.firstName = "Test"
        signUpuser?.zipCode = 380004
        signUpuser?.contactNumber = 12345
        signUpuser?.sex = "Test"
        signUpuser?.dob = "Test"
        signUpuser?.signupType = "Test"
        signUpuser?.verified = "Test"
        signUpuser?.emailTokenExpiration = "Test"
        signUpuser?.updatedAt = "Test"
        signUpuser?.createdAt = "Test"

if let jsonData = try? JSONSerialization.data(withJSONObject: signUpuser, options: []) {
            let theJSONText = String(data: jsonData, encoding: .utf8)
            AppLog.debug(tag: TAG, msg: theJSONText!)
        }

In Android using Google's gson library we can easily convert JSON to Object and vice versa but in iOS it seems bit difficult.

I also tried to wrap the SignupUser object inside other class object but no luck.

"Wrapping inside other class..."

let wrapperObject = JSONServerRequest(data: signUpuser)
        if let jsonData = try? JSONSerialization.data(withJSONObject: wrapperObject, options: []) {
            let theJSONText = String(data: jsonData, encoding: .utf8)
            AppLog.debug(tag: TAG, msg: theJSONText!)
        }

I don't wish to do this with Dictionary as I have to write the keys every time, I prefer to work with objects so If anyone has any clue please kindly guide me.

1
  • 1
    JSONSerialization.data(withJSONObject: expects a property list compliant array or dictionary. Custom objects are not supported. Commented Apr 4, 2017 at 11:24

1 Answer 1

6

Add this method in your model class

func toDictionary() -> [String : Any] {

    var dictionary = [String:Any]()
    let otherSelf = Mirror(reflecting: self)

    for child in otherSelf.children {

        if let key = child.label {
            dictionary[key] = child.value
        }
    }

    print("USER_DICTIONARY :: \(dictionary.description)")

    return dictionary
}

This will give the dictionary representation of your model class so you can access like youclassObj.toDictionary()

and follow as per requirement : Convert Dictionary to JSON in Swift

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.