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

3
  • 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. Commented Mar 28, 2018 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 Commented Mar 28, 2018 at 12:33
  • I will look into the status being optional.Thanks for correcting Commented Mar 28, 2018 at 12:38

2 Answers 2

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?
}
Sign up to request clarification or add additional context in comments.

1 Comment

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

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.