How to serialize or convert Swift objects to JSON?

后端 未结 9 1698
灰色年华
灰色年华 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

    0 讨论(0)
  • 2020-11-28 04:11

    Not sure if lib/framework exists, but if you would like to do it automatically and you would like to avoid manual labour :-) stick with MirrorType ...

    class U {
    
      var id: Int
      var name: String
    
      init(id: Int, name: String) {
        self.id = id
        self.name = name
      }
    
    }
    
    extension U {
    
      func JSONDictionary() -> Dictionary<String, Any> {
        var dict = Dictionary<String, Any>()
    
        let mirror = reflect(self)
    
        var i: Int
        for i = 0 ; i < mirror.count ; i++ {
          let (childName, childMirror) = mirror[i]
    
          // Just an example how to check type
          if childMirror.valueType is String.Type {
            dict[childName] = childMirror.value
          } else if childMirror.valueType is Int.Type {
            // Convert to NSNumber for example
            dict[childName] = childMirror.value
          }
        }
    
        return dict
      }
    
    }
    

    Take it as a rough example, lacks proper conversion support, lacks recursion, ... It's just MirrorType demonstration ...

    P.S. Here it's done in U, but you're going to enhance NSManagedObject and then you'll be able to convert all NSManagedObject subclasses. No need to implement this in all subclasses/managed objects.

    0 讨论(0)
  • 2020-11-28 04:13

    UPDATE: Codable protocol introduced in Swift 4 should be sufficient for most of the JSON parsing cases. Below answer is for people who are stuck in previous versions of Swift and for legacy reasons

    EVReflection :

    • This works of reflection principle. This takes less code and also supports NSDictionary, NSCoding, Printable, Hashable and Equatable

    Example:

        class User: EVObject { # extend EVObject method for the class
           var id: Int = 0
           var name: String = ""
           var friends: [User]? = []
        }
    
        # use like below
        let json:String = "{\"id\": 24, \"name\": \"Bob Jefferson\", \"friends\": [{\"id\": 29, \"name\": \"Jen Jackson\"}]}"
        let user = User(json: json)
    

    ObjectMapper :

    • Another way is by using ObjectMapper. This gives more control but also takes a lot more code.

    Example:

        class User: Mappable { # extend Mappable method for the class
           var id: Int?
           var name: String?
    
           required init?(_ map: Map) {
    
           }
    
           func mapping(map: Map) { # write mapping code
              name    <- map["name"]
              id      <- map["id"]
           }
    
        }
    
        # use like below
        let json:String = "{\"id\": 24, \"name\": \"Bob Jefferson\", \"friends\": [{\"id\": 29, \"name\": \"Jen Jackson\"}]}"
        let user = Mapper<User>().map(json)
    
    0 讨论(0)
提交回复
热议问题