簡體   English   中英

獲取密鑰的方法JSON響應(字符串)編碼投訴

[英]Get Method JSON Response(String) Coding Complaint for key

我的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:]:此類不符合鍵值編碼的鍵值。 請指導我獲取名稱,地址的值。

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

響應處理程序

響應處理程序不評估任何響應數據。 它僅直接轉發來自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 (檢查 ),以.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) 
    }            
}

有關編碼和解碼自定義類型的更多信息,請閱讀這篇文章

您可以嘗試將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 /軟件”,“商家類型”:“辦公室”}]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM