You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift解析NASA火星车照片JSON报错:数据格式不正确无法读取

问题原因

  • 你当前直接尝试将返回数据解析为[LatestPhoto]数组类型,但接口返回的JSON根节点是对象,数组是存放在根对象的latest_photos字段下的,类型不匹配直接导致解析失败。
  • 你的LatestPhoto结构体里自定义了id = UUID(),但JSON本身每个photo条目已经带有数值类型的id字段,你没有在CodingKeys里声明id的解析规则,也会存在解析冲突问题。

修复方案

1. 新增匹配JSON根结构的解析结构体

struct NasaPhotoResponse: Codable {
    let latestPhotos: [LatestPhoto]
    
    enum CodingKeys: String, CodingKey {
        case latestPhotos = "latest_photos"
    }
}

2. 修正LatestPhoto结构体

如果不需要自定义UUID作为id,直接解析接口返回的id即可,同时满足Identifiable协议要求:

struct LatestPhoto: Identifiable, Codable{
    let id: Int
    let imgSrc: String
    let earthDate: String

    enum CodingKeys: String, CodingKey {
        case id
        case imgSrc = "img_src"
        case earthDate = "earth_date"
    }
}

如果业务确实需要用UUID作为唯一标识,你可以保留let id = UUID()的写法,不需要把id加入CodingKeys即可,Codable会自动忽略有默认值且不在CodingKeys里的属性,不会影响解析。

3. 修改API的解析逻辑

先解析根结构,再取出照片数组返回:

import Foundation

class API {
    // 顺便修正原方法的参数名拼写错误
    class func getImage(_ onSuccess: @escaping ([LatestPhoto]) -> ()){
        Constrant.session.dataTask(with: Constrant.request){(data, res, err) in
            guard let data = data, err == nil else{
                fatalError()
            }
            do{
                let response = try Constrant.decoder.decode(NasaPhotoResponse.self, from: data)
                DispatchQueue.main.async {
                    onSuccess(response.latestPhotos)
                }
            }
            catch{
                // 调试时建议直接打印error,比localizedDescription的错误信息更完整
                print("解析错误详情:\(error)")
                fatalError(error.localizedDescription)
            }
            
        }.resume()
        
    }
}

内容的提问来源于stack exchange,提问作者Stan1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 20:06:07