简体   繁体   中英

Get Method JSON Response(String) Coding Complaint for key

My ResponseString is as follows,

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

My Get request code with headers is as follows,

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

      } }
}

When I tried to get the value for "name" its getting'[<__NSCFString 0x7b40f400> valueForUndefinedKey:]: this class is not key value coding-compliant for the key code. Please guide me to get the values of name, address..?????

You can use the Response Handler instead of 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
}

Also you can omit the coding keys from your struct declaration if you set your decoder keyDecodingStrategy (check this ) to .convertFromSnakeCase as already mentioned in comments by @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) 
    }            
}

For more information about encoding and decoding custom types you can read this post .

You can try to convert the json string to data then decode it

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 
}

Then

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

Note your str json may be invalid as you miss " after shop_types so make sure it looks like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM