获取密钥的方法JSON响应(字符串)编码投诉

时间:2018-11-24 14:44:47

标签: ios json string xcode swift4

我的ResponseString如下,

SUCCESS: 
{"code":200,"shop_detail":{"name":"dad","address":"556666"},
"shop_types : [{"name":"IT\/SOFTWARE","merchant_type":"office"}]}

我的带有标头的Get请求代码如下,

func getProfileAPI() {
        let headers: HTTPHeaders = [
            "Authorisation": AuthService.instance.tokenId ?? "",
            "Content-Type": "application/json",
            "Accept": "application/json"
        ]
        print(headers)
        let scriptUrl = "http://haitch.igenuz.com/api/merchant/profile"

        if let url = URL(string: scriptUrl) {
            var urlRequest = URLRequest(url: url)
            urlRequest.httpMethod = HTTPMethod.get.rawValue

            urlRequest.addValue(AuthService.instance.tokenId ?? "", forHTTPHeaderField: "Authorization")
            urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
            urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")

            Alamofire.request(urlRequest)
                .responseString { response in
                    debugPrint(response)
                    print(response)
                    if let result = response.result.value //    getting the json value from the server
                    {
                        print(result)

                        let jsonData1 = result as NSString
                        print(jsonData1)
                        let name = jsonData1.object(forKey: "code") as! [AnyHashable: Any]
                        print(name)
                       // var data = jsonData1!["shop_detail"]?["name"] as? String

      } }
}

当我尝试获取“名称”的值时,它会得到“ [<__ NSCFString 0x7b40f400> valueForUndefinedKey:]:此类不符合键值编码的键值。请指导我获取名称,地址.. ??????

的值

2 个答案:

答案 0 :(得分:3)

您可以使用响应处理程序代替响应字符串处理程序

  

响应处理程序

     

响应处理程序不评估任何响应数据。它   仅直接转发URL会话中的所有信息   代表。与使用cURL执行请求的Alamofire等效。

struct Root: Codable {
    let code: Int
    let shopDetail: ShopDetail
    let shopTypes: [ShopType]
}

struct ShopDetail: Codable {
    let name, address: String
}

struct ShopType: Codable {
    let name, merchantType: String
}

如果您将解码器keyDecodingStrategy(检查this)设置为.convertFromSnakeCase(如@vadian的注释中所述),则也可以从结构声明中省略编码键:


Alamofire.request(urlRequest).response { response in
    guard 
       let data = response.data, 
       let json = String(data: data, encoding: .utf8) 
    else { return }
    print("json:", json)
    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let root = try decoder.decode(Root.self, from: data)
        print(root.shopDetail.name)
        print(root.shopDetail.address)
        for shop in root.shopTypes {
            print(shop.name)
            print(shop.merchantType)
        }
    } catch { 
        print(error) 
    }            
}

有关编码和解码自定义类型的更多信息,请阅读此post

答案 1 :(得分:0)

您可以尝试将json字符串转换为数据,然后将其解码

struct Root: Codable {
    let code: Int
    let shopDetail: ShopDetail
    let shopTypes: [ShopType] 
}

struct ShopDetail: Codable {
    let name, address: String
}

struct ShopType: Codable {
    let name, merchantType: String 
}

然后

let jsonStr = result as! String
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try? dec.decode(Root.self,from:jsonStr.data(using:.utf8)!)

请注意,您在shop_types之后错过时,您的str json可能无效,因此请确保它看起来像这样

  

{“代码”:200,“ shop_detail”:{“名称”:“爸爸”,“地址”:“ 556666”},   “ shop_types”:[{“名称”:“ IT /软件”,“ merchant_type”:“办公室”}]}}