【问题标题】:How to parse enum with JASON pod?如何使用 JASON pod 解析枚举?
【发布时间】:2017-10-24 07:10:26
【问题描述】:

我从服务器获取 JSON。对于解析,我使用JASON 图书馆。 如何使用枚举值解析 JSON?

例子:

{
        ...
    "first_name": "John",
    "last_name": "Doe",
    "user_type": "basic"
        ...
}

“用户类型”在哪里:

enum UserType {
  case basic
  case pro
}

有人知道吗?

【问题讨论】:

  • 解析是什么意思?是否要从枚举变量中的 JSON 存储中获取值 user_type
  • 是的,你是对的

标签: ios json swift parsing


【解决方案1】:

如果你想在枚举中存储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)
}

【讨论】:

  • 如何使用 JASON lib 来实现?
【解决方案2】:

复制自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

【讨论】:

    【解决方案3】:

    如果您使用 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      相关资源
      最近更新 更多