无法在获取请求中解码带文本的json

时间:2018-07-23 12:41:54

标签: ios json swift decode

我需要这样创建GET请求:

https://public-api.nazk.gov.ua/v1/declaration/?q=Чер

https://public-api.nazk.gov.ua/v1/declaration/?q=Володимирович

=后的最后一个字符是西里尔符号

我让get请求是这样的:

 var hostURL = "https://public-api.nazk.gov.ua/v1/declaration/?q="
hostURL = hostURL + searchConditions

let escapedSearchConditions = hostURL.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)

let url = URL(string: escapedSearchConditions!)!

请求是: https://public-api.nazk.gov.ua/v1/declaration/?q=%D0%9F%D1%80%D0%BE

从服务器返回必要数据但无法解码的数据。
它适用于搜索条件下的整数,但不适用于西里尔字母(

import Foundation

struct Declarant: Codable {
var id: String
var firstname: String
var lastname: String
var placeOfWork: String
var position: String
var linkPDF: String

}

struct DeclarationInfo: Codable {
let items: [Declarant]

}

导入基金会

struct DeclarationInfoController {

func fetchDeclarationInfo (with searchConditions: String, completion: @escaping(DeclarationInfo?) -> Void) {
    var hostURL = "https://public-api.nazk.gov.ua/v1/declaration/?q="
    hostURL = hostURL + searchConditions

    let escapedSearchConditions = hostURL.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)

    let url = URL(string: escapedSearchConditions!)!

    print(url)

    let dataTask = URLSession.shared.dataTask(with: url) {
        (data, response, error) in
        let jsonDecoder = JSONDecoder()
        print("Trying to decode data...")

        if let data = data,
            let declarationInfo = try? jsonDecoder.decode(DeclarationInfo.self, from: data) {
            completion(declarationInfo)
            print(declarationInfo)
        } else {
            print("Either no data was returned, or data was not properly decoded.")
            completion(nil)
        }
    }

    dataTask.resume()
}


}


import UIKit

class DeclarationViewController: UIViewController {

let declarationInfoController = DeclarationInfoController()

@IBOutlet weak var searchBar: UISearchBar!

@IBOutlet weak var resultLabel: UILabel!


@IBAction func beginSearchButton(_ sender: UIButton) {
    declarationInfoController.fetchDeclarationInfo(with: searchBar.text!) { (declarationInfo) in
        if let declarationInfo = declarationInfo {
            DispatchQueue.main.async {
                self.resultLabel.text = declarationInfo.items[0].lastname
            }
        }
    }
}

}

2 个答案:

答案 0 :(得分:1)

从不永远不要使用try?来解码JSON时忽略错误。 Codable错误具有令人难以置信的描述性,可以准确告诉您出什么问题了。

始终使用 像{p>

do catch

并打印do { let declarationInfo = try jsonDecoder.decode(DeclarationInfo.self, from: data) } catch { print error } 而不是无用的文字字符串。


该错误与西里尔文字无关。

one of your previous questions注释中建议的JSON结构

error

显示错误(强调最重要的部分)

  

keyNotFound (CodingKeys(字符串值:“位置” ,intValue:无),Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ items “ ,intValue:无),_JSONKey(stringValue:”索引11“ ,intValue:11)],debugDescription:” 没有与键CodingKeys相关联的值(stringValue:\“ position \“ ,intValue:无)(\” position \“)。”,底层错误:nil))

它清楚地描述了在结构struct Item: Codable { let id, firstname, lastname, placeOfWork: String let position, linkPDF: String } 中,在数组索引11处的项Item没有值。

解决方案是将该特定的struct成员声明为可选

position

再次:不要忽略错误,它们会帮助您立即解决问题。

答案 1 :(得分:0)

更新

if let data = data,
            let declarationInfo = try? jsonDecoder.decode(DeclarationInfo.self, from: data) {
            completion(declarationInfo)
            print(declarationInfo)
        } else {
            print("Either no data was returned, or data was not properly decoded.")
            completion(nil)
        }

通过

 do {
       if let data = data {
        let declarationInfo = try jsonDecoder.decode(DeclarationInfo.self, from: data) 
        completion(declarationInfo)
        print(declarationInfo)
        return
    } catch {
        print(error) 
    }
    completion(nil)

您将打印出错误,并且您会知道解码失败的原因