0

I wish refresh the all class properties using json data obtained from an API when called. The code I wrote here works fine but imagine if you have a large number of stored properties, say 50,
then in loadJsonData(), you will have to define the property manually line by line, which isn't great. Is there a better way to do this?

struct loadUserData: View {
    @ObservedObject var someUser = SomeUser()

    var body: some View {
        
        
        VStack(alignment: .leading){
            TextField("Enter current user name", text: self.$someUser.name)
            Text("Name: \(someUser.name)")
            Button(action: {self.someUser.loadJsonData()}){
                Text("Load Json Data")
            }
        }
    }
}




class SomeUser: ObservableObject, Codable {
    @Published var name: String

    init(){
        self.name = "Emma"
    }
    
    
   
     func loadJsonData(){
        let newJson = "{\"name\":\"Jason\"}" // imagine this is what you get from API query
        let data = Data(newJson.utf8)
        guard let decoded = try? JSONDecoder().decode(SomeUser.self, from: data) else {
        print("something went wrong. newJson is \(newJson)")
        return
        }
        self.name = decoded.name
    }

    
    
    enum CodingKeys: String, CodingKey {
        case name
    }
    
    required init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decode(String.self, forKey: .name)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
    }
    
    
}
mic
  • 155
  • 2
  • 9
  • The greatest advantage of using `JSONDecoder` over `JSONSerialization` is that you can use a decodable struct to construct a data model. So why don't you? – El Tomato Jun 29 '20 at 03:30
  • Unfortunately, adding `@Published` disables the compiler's synthesis of conformance to `Codable` (because `Published<...>` isn't a conforming type). Look at https://stackoverflow.com/a/59918094/968155 for a way to make it conform (I haven't tried it) – New Dev Jun 29 '20 at 04:03

0 Answers0