如何序列化或将Swift对象转换为JSON?

时间:2015-04-13 06:25:22

标签: json swift

以下课程

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

需要转换为

{
    "id" : 98,
    "name" : "Jon Doe"
}

我尝试手动将对象传递给一个函数,该函数将变量设置为字典并返回字典。但我希望有更好的方法来实现这一目标。

8 个答案:

答案 0 :(得分:70)

在swift 4中,您可以继承Codable类型。

struct Dog: Codable {
    var name: String
    var owner: String
}

// Encode
let dog = Dog(name: "Rex", owner: "Etgar")

let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(dog)
let json = String(data: jsonData, encoding: String.Encoding.utf16)

// Decode
let jsonDecoder = JSONDecoder()
let dog = try jsonDecoder.decode(Dog.self, from: jsonData)

答案 1 :(得分:25)

对于大多数Codable解析案例,Swift 4中引入的

更新: JSON协议应该足够了。以下答案适用于以前版本的Swift和遗留原因卡住的人

EVReflection

  • 这是反射原理的作品。这需要较少的代码,并且还支持NSDictionaryNSCodingPrintableHashableEquatable

示例:

    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

  • 另一种方法是使用ObjectMapper。这样可以提供更多控制,但也需要更多代码。

示例:

    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)

答案 2 :(得分:22)

与Swift 4(Foundation)一起,它现在以两种方式本地支持,JSON字符串到对象 - JSON字符串的对象。 请在此处JSONDecoder()和此处JSONEncoder()

查看Apple的文档

JSON String to Object

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

Swift对象到JSONString

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

您可以在Ultimate Guide to JSON Parsing With Swift 4

找到所有详细信息和示例

答案 3 :(得分:13)

我在一个不需要继承的小型解决方案上做了一些工作。但它还没有经过多次测试。这是非常丑陋的atm。

https://github.com/peheje/JsonSerializerSwift

您可以将它传递到游乐场进行测试。例如。以下类结构:

//Test nonsense data
class Nutrient {
    var name = "VitaminD"
    var amountUg = 4.2

    var intArray = [1, 5, 9]
    var stringArray = ["nutrients", "are", "important"]
}

class Fruit {
    var name: String = "Apple"
    var color: String? = nil
    var weight: Double = 2.1
    var diameter: Float = 4.3
    var radius: Double? = nil
    var isDelicious: Bool = true
    var isRound: Bool? = nil
    var nullString: String? = nil
    var date = NSDate()

    var optionalIntArray: Array<Int?> = [1, 5, 3, 4, nil, 6]
    var doubleArray: Array<Double?> = [nil, 2.2, 3.3, 4.4]
    var stringArray: Array<String> = ["one", "two", "three", "four"]
    var optionalArray: Array<Int> = [2, 4, 1]

    var nutrient = Nutrient()
}

var fruit = Fruit()
var json = JSONSerializer.toJson(fruit)

print(json)

打印

{"name": "Apple", "color": null, "weight": 2.1, "diameter": 4.3, "radius": null, "isDelicious": true, "isRound": null, "nullString": null, "date": "2015-06-19 22:39:20 +0000", "optionalIntArray": [1, 5, 3, 4, null, 6], "doubleArray": [null, 2.2, 3.3, 4.4], "stringArray": ["one", "two", "three", "four"], "optionalArray": [2, 4, 1], "nutrient": {"name": "VitaminD", "amountUg": 4.2, "intArray": [1, 5, 9], "stringArray": ["nutrients", "are", "important"]}}

答案 4 :(得分:7)

这不是一个完美/自动的解决方案,但我相信这是惯用和原生的方式。这样您就不需要任何库等。

创建协议,例如:

/// A generic protocol for creating objects which can be converted to JSON
protocol JSONSerializable {
    private var dict: [String: Any] { get }
}

extension JSONSerializable {
    /// Converts a JSONSerializable conforming class to a JSON object.
    func json() rethrows -> Data {
        try JSONSerialization.data(withJSONObject: self.dict, options: nil)
    }
}

然后在你的课程中实现它,例如:

class User: JSONSerializable {
    var id: Int
    var name: String

    var dict { return ["id": self.id, "name": self.name]  }
}

现在:

let user = User(...)
let json = user.json()

注意:如果您希望将json作为字符串,则只需转换为字符串即可:String(data: json, encoding .utf8)

答案 5 :(得分:3)

上面的一些答案是完全可以的,但是我在这里添加了一个扩展名,只是为了使其更具可读性和可用性。

extension Encodable {
    var convertToString: String? {
        let jsonEncoder = JSONEncoder()
        jsonEncoder.outputFormatting = .prettyPrinted
        do {
            let jsonData = try jsonEncoder.encode(self)
            return String(data: jsonData, encoding: .utf8)
        } catch {
            return nil
        }
    }
}

struct User: Codable {
     var id: Int
     var name: String
}

let user = User(id: 1, name: "name")
print(user.convertToString!)

//这将打印如下:

{
  "id" : 1,
  "name" : "name"
}

答案 6 :(得分:2)

不确定lib / framework是否存在,但是如果你想自动完成它并且你想避免手工劳动:-)坚持使用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
  }

}

把它作为一个粗略的例子,缺乏适当的转换支持,缺乏递归,......这只是MirrorType演示......

P.S。这是在U中完成的,但您将增强NSManagedObject,然后您将能够转换所有NSManagedObject子类。无需在所有子类/托管对象中实现此功能。

答案 7 :(得分:0)

struct User:Codable{
 var id:String?
 var name:String?
 init(_ id:String,_ name:String){
   self.id  = id
   self.name = name
 }
}
  

现在只需像这样使您的对象

让用户= User(“ 1”,“ pawan”)

do{
      let userJson = data: try JSONEncoder().encode(parentMessage), encoding:.utf8)

    }catch{
         fatalError("Unable To Convert in Json")      
    }
  

然后从json转换为Object

let jsonDecoder = JSONDecoder()
do{
   let convertedUser = try jsonDecoder.decode(User.self, from: userJson.data(using: .utf8)!)
 }catch{

 }