ios - 获取要在文本字段中显示的方法 JSON 数据不起作用(错误)

标签 ios json swift

如何通过 GET 方法获取文本字段中的 JSON 数据。我的Json数据如下,

    SUCCESS: {"code":200,
"shop_detail":{"name":"dad","address":"556666","city":"cSC","area":"scsc","street":"vddva","building":"jhkj","description":null}

 "shop_types":
[{"id":7,"name":"IT\/SOFTWARE","merchant_type":"office",}]}

我的带有标题和 URL 的代码是

 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
                    {

    }
}

打印响应后,如果我有 name.text、address.text 等文本字段,我将打印 JSON 数据的值。我想显示通过 JSON 响应得到的值。如果我尝试下面的代码,它在字典中会失败。

if let data = data {
                print(data)
                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: [])
                    let jsonData:NSDictionary = (data as? NSDictionary)!
                    print(jsonData)
}}

最佳答案

试试这个,

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

struct ShopDetail: Codable {
    let name, address, area, street, building, city: String
}

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

并调用

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).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)
                    self.t1.text! = root.shopDetail.name
                 //   self.t3.text! = root.shopDetail.description
                    print(root.shopDetail.name)
                    print(root.shopDetail.address)
                    for shop in root.shopTypes {
                        self.merchant_Type.text! = shop.merchantType
                        self.t2.text! = shop.name
                        print(shop.name)
                        print(shop.merchantType)
                    }
                } catch {
                    print(error)
                }
            }}}

关于ios - 获取要在文本字段中显示的方法 JSON 数据不起作用(错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53440541/

相关文章:

ios - 在自动布局中自动更新框架

python - 为什么我的 JSON 输出中有一堆反斜杠

ios - 我们可以在 Swift 上重用结构吗?或者还有其他办法吗?

ios - uitableViewCell 图像到新 View

ios - 如何从冷启动调试打开通用链接?

ios - CoreData 堆栈 [child(background)/parent(thread 1)] setup mergeChangesFromContextDidSaveNotification 不更新 UI(tableview)

ios - Swift/iOS - 在较小的屏幕上触发 ScrollView

ios - 快速从类(class)中执行转场

ios - 防止 MPMoviePlayerController 控件在视频开始时显示

javascript - 尝试使用 jquery ajax 但无法解析 JSON?