我从服务器获取JSON。对于解析,我使用JASON 图书馆。 如何用枚举值解析JSON?
示例:
{
...
"first_name": "John",
"last_name": "Doe",
"user_type": "basic"
...
}
其中' user_type':
enum UserType {
case basic
case pro
}
有没有人有任何想法?
答案 0 :(得分:2)
如果要在枚举中存储user_type
的值:
将您的枚举变量类型更改为字符串:
enum UserType: String {
case basic = "basic"
case pro = "pro"
}
解决方案,不使用JASON
将您的JSON存储到字典类型变量中:
let jsonVar = [
"first_name": "John",
"last_name": "Doe",
"user_type": "basic"
] as [String : Any]
现在,从字典变量中获取值并使用原始值创建枚举变量:
if let user_type = jsonVar["user_type"] as? String {
let usertype = UserType(rawValue: user_type)
}
解决方案,使用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)
}
答案 1 :(得分:0)
从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
答案 2 :(得分:0)
如果使用Swift 4,则有一个有用的默认JSONDecoder。举个例子:
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)