How to serialize or convert Swift objects to JSON?

后端 未结 9 1740
灰色年华
灰色年华 2020-11-28 03:33

This below class

class User: NSManagedObject {
  @NSManaged var id: Int
  @NSManaged var name: String
}

Needs to be converted to

9条回答
  •  旧巷少年郎
    2020-11-28 04:05

    Along with Swift 4 (Foundation) now it is natively supported in both ways, JSON string to an object - an object to JSON string. Please see Apple's documentation here JSONDecoder() and here JSONEncoder()

    JSON String to Object

    let jsonData = jsonString.data(using: .utf8)!
    let decoder = JSONDecoder()
    let myStruct = try! decoder.decode(myStruct.self, from: jsonData)
    

    Swift Object to JSONString

    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    let data = try! encoder.encode(myStruct)
    print(String(data: data, encoding: .utf8)!)
    

    You can find all details and examples here Ultimate Guide to JSON Parsing With Swift 4

提交回复
热议问题