2

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

  • You cannot decode `Any(Object)` with Codable. At least you have to write a custom initializer to determine the concrete type(s). By the way: In Swift you don’t need classes inherited from `NSObject` in most cases. And why is `status` optional? Most likely the API is always sending this key. – vadian Mar 28 '18 at 11:35
  • Yes I understand it doesnt decode Any(Object) but then 1.I have to get json from from received data using JSONSerialization.jsonObject( with: data! , options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary 2. again serailize the records using JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) 3.Finally decoder.decode([entCustomer].self, from: data) to get actual records of the specific entity – shravan agrawal Mar 28 '18 at 12:33
  • I will look into the status being optional.Thanks for correcting – shravan agrawal Mar 28 '18 at 12:38

2 Answers2

3

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?
}
fmnavarretem
  • 151
  • 1
  • 4
  • 1
    Can you explain why this change works? Code only answers are rarely helpful to other users and usually get deleted. This is especially true with old questions like this, since the OP has already solved or moved on from their problem, and so the value of your answer is for future people with the same problem. – divibisan Aug 14 '18 at 20:02
0

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.
}
rockdaswift
  • 9,613
  • 5
  • 40
  • 46