Reputation: 79
I am trying to parse JSON using Codable in swift 4. My concern is
public class entStatusAndDescription : NSObject {
var status : Int?
var statusDescription : String?
var records : AnyObject?
}
I want the above entity to be codable but the "records" cant be specific entity, as this is my base entity that I will receive from API. After I parse the status and statusDescription, only then I can specify which entity will records be
e.g I am calling API for customer details and i receive status as 200 i.e success then I will parse records to Customer entity
Upvotes: 2
Views: 4742
Reputation: 171
A class is Codable if all its members are Codable. When you use a Generic member, you have to be sure that this member is Codable. In that case, you can create objects where records member be any, always than records inherit from Codable.
This is working for me:
public class entStatusAndDescription<T: Codable>: Codable {
var status : Int?
var statusDescription : String?
var records : T?
}
Upvotes: 3
Reputation: 9983
Solved using the good old JSONSerialization:
let data = "[{\"key\": \"value\"}]".data(using: .utf8)
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let json = json as? [String: Any] {
// parse as needed, a value can be of type Any.
}
Upvotes: 0