Swift 4 json解码器错误flickr

mas*_*rqp 7 json json-deserialization swift swift4

我在swift 4中尝试新的JSONDecoder()并尝试解析以下flickr API响应:(https://api.flickr.com/services/rest/?api_key=api_key&method=flickr.photos.search&format=json&per_page = 25&text = hello&nojsoncallback = 1).但是我得到一个错误,说"处理json数据时出错:由于数据格式不正确,无法读取数据." 但是数据似乎对我来说格式正确.我做错了吗?

            let dataTask = session.dataTask(with: urlRequest) { (data, response, error) in
                if let error = error {
                    print("json error: \(error.localizedDescription)")
                    return
                } else if let data = data {
                    print(response)
                    do {
                        let decoder = JSONDecoder()
                        print(data)
                        let flickrPhotos = try decoder.decode(FlickrImageResult.self, from: data)
                    } catch {
                        dump(data)
                        print("json error: \(error.localizedDescription)")
                    }
                }
            }
            dataTask.resume()
Run Code Online (Sandbox Code Playgroud)

我的数据模型是

struct FlickrImageResult : Codable {
     var photos : FlickrPhoto? = nil

}

struct FlickrPhoto : Codable {
    var photo : [FlickrURLs]? = nil
 }

struct FlickrURLs: Codable {
    var id : String? = nil
    var owner: String? = nil
    var secret: String? = nil
    var server: String? = nil
    var farm: String? = nil
}
Run Code Online (Sandbox Code Playgroud)

我将请求的图像数量更改为2并打印出数据返回可选({"照片":{"page":1,"pages":120197,"perpage":2,"total":"240393","照片 ":[{" ID ":" 36729752762" , "主人": "152440263 @ N02", "秘密": "e62ba3e18b", "服务器": "4432", "农场":5, "称号":"你好那里","ispublic":1,"isfriend":0,"isfamily":0},{"id":"36729384952","所有者":"141041947 @ N06","秘密":"bc0e5af630", "server":"4380","farm":5,"title":"POST\ud83d\udd25#891 | Hello Tuesday | Krescendo","ispublic":1,"isfriend":0,"isfamily":0 }]}, "STAT": "OK"})

nat*_*han 15

你的模型唯一的问题是它farm实际上是一个问题Int.这是一个更完整的模型版本,适用于文档(https://www.flickr.com/services/api/flickr.photos.search.html):

struct FlickrImageResult: Codable {
    let photos : FlickrPagedImageResult?
    let stat: String
}

struct FlickrPagedImageResult: Codable {
    let photo : [FlickrURLs]
    let page: Int
    let pages: Int
    let perpage: Int
    let total: String
}

struct FlickrURLs: Codable {
    let id : String
    let owner: String
    let secret: String
    let server: String
    let farm: Int
    // let title: String
    // If needed, camel-case and use CodingKeys enum
    //let ispublic: Int
    //let isfriend: Int
    //let isfamily: Int
}

let jsonData = """
{
  "photos": {
    "page": 1,
    "pages": 13651,
    "perpage": 25,
    "total": "341263",
    "photo": [
      {
        "id": "36499638920",
        "owner": "55126206@N07",
        "secret": "7e82dee0ba",
        "server": "4346",
        "farm": 5,
        "title": "[BREATHE]-Ririko,Sayaka&Chiyoko",
        "ispublic": 1,
        "isfriend": 0,
        "isfamily": 0
      },
      {
        "id": "36724435032",
        "owner": "92807782@N04",
        "secret": "6d830d4a75",
        "server": "4354",
        "farm": 5,
        "title": "Serendipity Designs @ SWANK August 2017",
        "ispublic": 1,
        "isfriend": 0,
        "isfamily": 0
      },
      {
        "id": "36087089863",
        "owner": "152685136@N08",
        "secret": "a4a3f2fe0a",
        "server": "4365",
        "farm": 5,
        "title": "Hello Kitty Scooter",
        "ispublic": 1,
        "isfriend": 0,
        "isfamily": 0
      },
      {
        "id": "36086949593",
        "owner": "151818203@N02",
        "secret": "fc1207d373",
        "server": "4334",
        "farm": 5,
        "title": "Hip, Hip! It's Chip!",
        "ispublic": 1,
        "isfriend": 0,
        "isfamily": 0
      },
      {
        "id": "36498504410",
        "owner": "148300038@N02",
        "secret": "5c7f6ff3e1",
        "server": "4391",
        "farm": 5,
        "title": "Hello Kotti",
        "ispublic": 1,
        "isfriend": 0,
        "isfamily": 0
      }
    ]
  },
  "stat": "ok"
}
""".data(using: .utf8)!

let flickrPhotos = try! JSONDecoder().decode(FlickrImageResult.self, from: jsonData)
print(flickrPhotos)
Run Code Online (Sandbox Code Playgroud)


PS:该消息error processing json data: The data couldn’t be read because it isn’t in the correct format.是本地化的错误信息,print(error)的,而不是print(errorlocalizedDescription)获取所有可用的错误数据(在你的情况下,将打印有一个问题,试图解码农场键时).

  • 没关系,这是一个JSON编码问题(farm是一个Int not String).在调试时,不要使用`error.localizedDescription`而是`print("json error:\(error)")`.它将提供更多信息. (3认同)