简体   繁体   中英

How to convert array object to JSON string . IOS 8 . Swift 1.2

I got an array of object like this

    var AuditActivityDayListJson =  Array<AuditActivityDayModel>()


    class AuditActivityDayModel : Serializable {
    var DayNumber : Int
    var DayType : Int
    var DayDateDisplay : String
    var DayDate : String

    override init() {
        DayNumber = 0
        DayType = 0
        DayDateDisplay = ""
        DayDate = ""
    }
}

How can i convert it into json string like this

[{"DayType":1,"DayNumber":1,"DayDate":"2015-06-30", "DayDateDisplay":""},{"DayType":1,"DayNumber":2,"DayDate":"2015-07-01","DayDateDisplay":""}]

Thanks all for your answer . Please help.

If you want to use builtin functions like NSJSONSerialization ( https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/ ) you basically need to convert all your objects to arrays, dictionaries, strings and numbers

In your case this should work, converting your objects to dictionaries before converting to a JSON string:

    let jsonCompatibleArray = AuditActivityDayListJson.map { model in
        return [
            "DayNumber":model.DayNumber,
            "DayType":model.DayType,
            "DayDateDisplay":model.DayDateDisplay,
            "DayDate":model.DayDate
        ]
    }
    let data = NSJSONSerialization.dataWithJSONObject(jsonCompatibleArray, options: nil, error: nil)
    let jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding)

For more complex scenarios I recommend SwiftyJSON ( https://github.com/SwiftyJSON/SwiftyJSON ) which makes error handling and more much easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM