ios - 获取键的方法 JSON 响应(字符串)编码投诉

标签 ios json string xcode swift4

我的ResponseString如下,

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

我的带有headers的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

      } }
}

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

最佳答案

您可以使用Response Handler 代替Response String Handler:

Response Handler

The response handler does NOT evaluate any of the response data. It merely forwards on all information directly from the URL session delegate. It is the Alamofire equivalent of using cURL to execute a Request.

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 ,您也可以省略结构声明中的编码键,正如@评论中已经提到的那样瓦迪安:


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 .

关于ios - 获取键的方法 JSON 响应(字符串)编码投诉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53459301/

相关文章:

javascript - 将多个对象数组连接成一个并在函数外部使用

c++ - 检查 std::any 变量是否包含 std::string 时出现问题

PHP处理大字符串

php - 如何减少很长字符串的长度?

ios - 如何通过 NSDate 对 NSMutableDictionary 中的 "key"和 "value"进行排序?

ios - Swift,电话号码正则表达式

ios - AVAssetExportSession 卡住(未启动)导出

ios - 使用 FaSTLane 将您的 IPA 文件上传到内部服务器

javascript - 将对象插入并对象 Javascript

java - StAXON - 当 autoPrimitive 为 true 时,强制将特定值设置为 String