如何将模型对象转换为JSON - Swift 4

时间:2018-01-25 05:28:39

标签: ios json class object swift4

如何将模型对象转换为JSON?
我想要“回答”对象。

//答案类

class Answers {

    var cat_id: String!
    var responses = [Response]()
    var date: String!
    var comment: String!
    var time: String!
    var lat: String!
    var lon: String!
    var address: String!

}

//响应类

class Response {

    var que_id: String!
    var question: String!
    var response: String!

}

2 个答案:

答案 0 :(得分:2)

使两种类型都符合Codable

class Answers: Codable {
    ...
}

class Response: Codable {
    ...
}

然后使用JSONEncoder

let answers: Answers = ...

do {
    let data = try JSONEncoder().encode(answers)
    // use data here
} catch {
    print(error)
}

请参阅Encoding and Decoding Custom Types

答案 1 :(得分:1)

如果您使用的是swift4,则可以使用可编码和可解码的协议。我还在研究一个异构的对象列表。但这对你有用。让您的课程符合protocol ABDecodable: Decodable { static func decodeFromData(_ data: Data) -> Decodable? } protocol ABEncodable: Encodable { static func encodeFromObject<T>(_ object: T) -> Data? where T: Encodable } extension ABDecodable { static func decodeFromData(_ data: Data) -> Decodable? { do { return try JSONDecoder().decode(self, from: data) } catch { print(error) } return nil } } extension ABEncodable { static func encodeFromObject<T>(_ object: T) -> Data? where T: Encodable { do { return try JSONEncoder().encode(object) } catch { return nil } } } //MARK: Decode mapper class //Send jsonString or data to decode it into an required Object final class Decode<T: Decodable> { private func decodeData(_ data: Data) -> T? { if let klass = T.self as? ABDecodable.Type { if let object = klass.decodeFromData(data) as? T { return object } } else { do { return try JSONDecoder().decode(T.self, from: data) } catch { print(error) } } return nil } func fromJsonString(_ json: String) -> T? { guard let data = json.data(using: String.Encoding.utf8) else { return nil } if let object = decodeData(data) { return object } return nil } func fromData(_ data: Data) -> T? { if let object = decodeData(data) { return object } return nil } } //MARK: Encode mapper class //Send jsonString or data to decode it into an required Object final class Encode<N:Encodable> { private func encodeObject(_ object: N) -> Data? { if let klass = N.self as? ABEncodable.Type { if let data = klass.encodeFromObject(object) { return data } } else { do { return try JSONEncoder().encode(object) } catch { print(error) } } return nil } func toJsonString(_ object: N) -> String? { if let data = encodeObject(object) { return String(data: data, encoding: .utf8) } return nil } func toData(_ object: N) -> Data? { if let data = encodeObject(object) { return data } return nil } }

{{1}}