-1

How to Convert a model object into JSON?
I want "Answer" object.

// Answers Class

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!

}

// Response Class

class Response {

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

}
Mohammad Razipour
  • 3,643
  • 3
  • 29
  • 49
  • Possible duplicate of [How to serialize or convert Swift objects to JSON?](https://stackoverflow.com/questions/29599005/how-to-serialize-or-convert-swift-objects-to-json) – Lal Krishna Jan 25 '18 at 05:31
  • Try this :https://stackoverflow.com/a/10548511/5167909 – Faysal Ahmed Jan 25 '18 at 05:32
  • 1
    Not related but **NEVER** declare properties in a class as implicit unwrapped optionals as an alibi not to write an initializer. Either the properties are supposed to be optional then declare them as regular optional (`?`) otherwise as non-optional (no question and exclamation mark) – vadian Jan 25 '18 at 06:09

2 Answers2

3

Make both types conform to Codable:

class Answers: Codable {
    ...
}

class Response: Codable {
    ...
}

And then use JSONEncoder:

let answers: Answers = ...

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

See Encoding and Decoding Custom Types.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
1

if you are using swift4, You can use encodable and decodable protocol. I'm still working on a heterogeneous list of objects. But this should work for you. Make your class conform to ABEncodable.

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
    }
}
Abhijit
  • 384
  • 3
  • 12