我如何在Swift 4中使用以下简单的JsonObject?我需要代码和消息的价值

时间:2018-09-04 10:16:14

标签: json swift

//这是我需要解析的json响应。

//我需要以下代码值作为条件。

 {
   Code = 0;
   Message = "Login Fail";
 }

2 个答案:

答案 0 :(得分:1)

转发,发布的原始数据结构不符合规范,并且不是JSON返回对象

{
  Code = 0;
  Message = "Login Fail";
}

转换为JSON

{
 "Code" : 0,
 "Message" : "Login Fail"
}

Swift 4具有一个非常好的协议,称为DecodableJSONDecoder。这些是Foundation的新功能。

步骤1:创建符合Decodable的结构或类

struct ErrorResponse: Decodable {
   var code: String?
   var message: String?
   enum CodingKeys : String, CodingKey {
       case code = "Code"
       case message = "Message"
   }
}

不使用可选选项的替代声明

struct ErrorResponse: Decodable {
   var code: String
   var message: String
   enum CodingKeys : String, CodingKey {
       case code = "Code"
       case message = "Message"
   }
}

Apple还提供了正确使用DecodableCodingKey here

的许多示例。

通知:此处如何使用CodingKeys表示小写但从服务器接收到的属性是大写的。您可以使用CodingKey对属性进行编码和解码,以符合您自己的命名约定。

第2步:使用JSONDecoder

guard let responseError = try? JSONDecoder().decode(ErrorResponse.self, from: data) else {
  print("Error: Could not parse JSON")
  return
}
print("code: \(responseError.code)")
print("message: \(responseError.message)")

答案 1 :(得分:-1)

好吧,您可以使用ObjectMapper swift库轻松地将对象模型与JSON相互转换:

要对其进行分解:

  1. 使用CocoaPods将ObjectMapper库添加到您的项目中:

        pod 'ObjectMapper', '~> 3.3'
    
  2. 定义实现Mappable协议的新类或结构(模型),并指出您必须通过实现他的两个方法来遵守Mappable协议:

    class Response: Mappable {
    
        var code: Int?
        var message: String?
    
        required init?(map: Map) { }
    
         // Mappable
        func mapping(map: Map) {
           code            <- map["code"]
           message         <- map["message"]
        }
      }
    
  3. 解析API响应并将Dictionary响应转换为响应模型对象:

    if let data = resultDictionary["response"] as? Dictionary<String, AnyObject> {
    
                   let  response = Mapper<Response>().map(JSONObject: data)
    
                    print("code = \(response.code)")
                    print("message = \(response.message.)")
       }
     }
    

响应模型是可映射的对象,其中包含代码和消息。