2016-02-18 83 views
1

我有以下需要使用Xcode 7及更高版本轉換爲JSON字符串的類。在以前版本的Xcode中,有一個JSONSerelization.toJson(AnyObject)函數可用,但是不會出現在Xcode7中。從Xcode 7+中的Swift對象創建JSON字符串

我需要轉換下面的類:

struct ContactInfo 
{ 
    var contactDeviceType: String 
    var contactNumber: String 
} 

class Tradesmen 
{ 
    var type:String = "" 
    var name: String = "" 
    var companyName: String = "" 
    var contacts: [ContactInfo] = [] 

init(type:String, name:String, companyName:String, contacts [ContactInfo]) 
    { 
     self.type = type 
     self.name = name 
     self.companyName = companyName 
     self.contacts = contacts 
    } 

我已經建立了我的測試數據如下

contactType = 
     [ 
      ContactInfo(contactDeviceType: "Home", contactNumber: "(604) 555-1111"), 
      ContactInfo(contactDeviceType: "Cell", contactNumber: "(604) 555-2222"), 
      ContactInfo(contactDeviceType: "Work", contactNumber: "(604) 555-3333") 
     ] 




var tradesmen = Tradesmen(type: "Plumber", name: "Jim Jones", companyName: "Jim Jones Plumbing", contacts: contactType) 

任何幫助或方向將不勝感激。

回答

0

我不認爲有任何直接的方式,即使在以前的Xcode。你將需要編寫你自己的實現。類似下面:

protocol JSONRepresenatble { 
    static func jsonArray(array : [Self]) -> String 
    var jsonRepresentation : String {get} 
} 

extension JSONRepresenatble { 
    static func jsonArray(array : [Self]) -> String { 
     return "[" + array.map {$0.jsonRepresentation}.joinWithSeparator(",") + "]" 
    } 
} 

然後在你的情態動詞實現JSONRepresentable象下面這樣:

struct ContactInfo: JSONRepresenatble { 
    var contactDeviceType: String 
    var contactNumber: String 
    var jsonRepresentation: String { 
     return "{\"contactDeviceType\": \"\(contactDeviceType)\", \"contactNumber\": \"\(contactNumber)\"}" 
    } 
} 

struct Tradesmen: JSONRepresenatble { 
    var type:String = "" 
    var name: String = "" 
    var companyName: String = "" 
    var contacts: [ContactInfo] = [] 
    var jsonRepresentation: String { 
     return "{\"type\": \"\(type)\", \"name\": \"\(name)\", \"companyName\": \"\(companyName)\", \"contacts\": \(ContactInfo.jsonArray(contacts))}" 
    } 
    init(type:String, name:String, companyName:String, contacts: [ContactInfo]) { 
     self.type = type 
     self.name = name 
     self.companyName = companyName 
     self.contacts = contacts 
    } 
}