-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!

}
3
  • Possible duplicate of How to serialize or convert Swift objects to JSON? Commented Jan 25, 2018 at 5:31
  • Try this :stackoverflow.com/a/10548511/5167909 Commented Jan 25, 2018 at 5: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) Commented Jan 25, 2018 at 6:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.