Reputation: 47
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.
Upvotes: 2
Views: 10039
Reputation: 1496
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.
Upvotes: 5