Reputation: 478
I get JSON from a server. For parsing, I use JASON library. How can I parse JSON with enum value?
Example:
{
...
"first_name": "John",
"last_name": "Doe",
"user_type": "basic"
...
}
Where 'user_type':
enum UserType {
case basic
case pro
}
Does anyone have any idea?
Upvotes: 1
Views: 400
Reputation: 228
If you work with Swift 4 there is useful default JSONDecoder. With your example:
import Foundation
let jsonDict = [
"first_name": "John",
"last_name": "Doe",
"user_type": "basic"
]
let jsonData = try! JSONSerialization.data(withJSONObject: jsonDict, options: [])
enum UserType: String, Codable {
case basic
case pro
}
struct User: Codable {
let firstName : String
let lastName: String
let userType: UserType
enum CodingKeys : String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
case userType = "user_type"
}
}
let decoder = JSONDecoder()
let user = try! decoder.decode(User.self, from: jsonData)
print(user)
Upvotes: 0
Reputation:
If you want to store value of user_type
in enum:
Change your enum variable type into string:
enum UserType: String {
case basic = "basic"
case pro = "pro"
}
Solution, without using JASON
Store your JSON into dictionary type variable:
let jsonVar = [
"first_name": "John",
"last_name": "Doe",
"user_type": "basic"
] as [String : Any]
Now, get a value from dictionary variable and create enum variable using raw value:
if let user_type = jsonVar["user_type"] as? String {
let usertype = UserType(rawValue: user_type)
}
Solution, using JASON
let json = [
"first_name": "John",
"last_name": "Doe",
"user_type": "basic"
] as AnyObject
let jasonVar = JSON(json)
if let user_type:String = jasonVar["user_type"].string {
let usertype = UserType(rawValue: user_type)
}
Upvotes: 2
Reputation: 980
Copied from How to get enum from raw value in Swift?
enum TestEnum: String {
case Name = "Name"
case Gender = "Gender"
case Birth = "Birth Day"
}
let name = TestEnum(rawValue: "Name")! //Name
let gender = TestEnum(rawValue: "Gender")! //Gender
let birth = TestEnum(rawValue: "Birth Day")! //Birth
Upvotes: 0