我有一个像这样的对象数组
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 = ""
}
}
如何将其转换为像这样的json字符串
[{"DayType":1,"DayNumber":1,"DayDate":"2015-06-30", "DayDateDisplay":""},{"DayType":1,"DayNumber":2,"DayDate":"2015-07-01","DayDateDisplay":""}]
感谢大家的回答。请帮忙。
答案 0 :(得分:4)
如果你想使用像NSJSONSerialization这样的内置函数( https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/) 你基本上需要将所有对象转换为数组,字典,字符串和数字
在你的情况下,这应该有效,在转换为JSON字符串之前将对象转换为字典:
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)
对于更复杂的场景,我建议使用SwiftyJSON(https://github.com/SwiftyJSON/SwiftyJSON),这样可以更容易地处理错误。