0

I'm making a framework. I want to convert server response JSON using Codable protocol. But it have [String:Any] value. How can I clear the Error? Type 'Person' does not conform to protocol 'Encodable'

public class Person: Codable {
    public var name: String?
    public var age: Int?
    public var userOriginalData: [String:Any]? // [String:Any]? or data? or Row JSON string
}
Maiko Ohkawa
  • 853
  • 2
  • 11
  • 28

1 Answers1

-1

Hi Please check my Answer I am not getting any error.

  import UIKit
    struct Website : Decodable {
        let name : String
        let description : String
        let courses : [Course]
    }
    struct Course : Decodable {
        let id : Int?
        let name : String?
        let link : String?
        let imageUrl : String?
    }

    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            getStartedBtn.setTitle(GetStarted, for: .normal)
            // Do any additional setup after loading the view, typically from a nib.
            self.callAPI()
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        func callAPI(){
            let urlString = "https://api.letsbuildthatapp.com/jsondecodable/website_description"
            guard let url = URL.init(string: urlString) else {
                return
            }
            URLSession.shared.dataTask(with: url) { (data, response, error) in
                guard let data = data else {
                    return
                }
                do {
                let web = try JSONDecoder().decode(Website.self, from: data)
                print(web.courses[0])
                }
                catch let error {
                print("error",error)
            }
        }.resume()
        }
    }
Mahesh kumar
  • 278
  • 4
  • 15
  • The answer is not related to the question at all. – vadian Jan 25 '18 at 10:13
  • You can use codable instead of Decodable because it is typealias – Mahesh kumar Jan 25 '18 at 10:33
  • If public var userOriginalData: [String:Any]? .. userOriginalData is dictionary so you simply create a userOriginalData as class or structure and it confirms Decodable protocol and JSONCoder() automatically parse your data. – Mahesh kumar Jan 25 '18 at 10:37
  • Thank you Mahesh kumar. However I can't know a structure of `userOriginalData` and it will change by user. Because I'm making a framework and `userOriginalData`'s structure is defined by user. Thanks anyway. – Maiko Ohkawa Jan 26 '18 at 05:23