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

解析Google Maps API JSON时,获取photoReference字段报错求助

问题解析:Google Maps API JSON解码后无法获取photoReference字段

问题场景

你定义了如下Codable结构体用于解码Google Maps API返回的JSON:

// MARK: - Welcome
struct POIData: Codable {
    let results: [Result]
}

// MARK: - Result
struct Result: Codable {
    let geometry: Geometry
    let name: String
    let place_id: String
    let photos: [Photo]
}

// MARK: - Geometry
struct Geometry: Codable {
    let location: Location
}

// MARK: - Location
struct Location: Codable {
    let lat, lng: Double
}

// MARK: - Photo
struct Photo: Codable {
    let photoReference: String
}

获取name字段的代码可正常运行:

cell.cellText.text = searchApi.dataFromSearchApi[indexPath.row].name

但获取photoReference时触发错误:Value of type '[Photo]' has no member 'photoReference',报错代码如下:

cell.cellCategory.text = searchApi.dataFromSearchApi[indexPath.row].photos.photoReference

附API返回的JSON片段:

"results": [
    {
      "name": "xxx",
      "opening_hours": {
        "open_now": true
      },
      "photos": [
        {
          "height": 900,
          "html_attributions": [
            "<a href=\"h"
          ],
          "photo_reference": "Axxx",
          "width": 1600
        }
      ],
      "place_id": "xxxx"
    }
]

错误原因

  1. 数组类型访问错误:Result结构体里的photos是[Photo]数组类型,你直接通过.photos.photoReference访问,相当于给数组对象调用单个Photo实例的属性,数组本身没有这个成员,因此报错。
  2. 字段名映射缺失:JSON中的字段是photo_reference,但你结构体里定义的是photoReference,默认Codable会严格匹配名称和大小写,不添加映射的话,解码后photoReference会是nil(属性为可选类型时)或直接解码失败(属性为必选类型时)。

修复方案

1. 修正数组访问方式

数组不能直接访问单个元素的属性,需先获取数组中的某个Photo实例,比如取第一个元素(注意处理可选值,避免数组为空时崩溃):

// 取第一个照片的photoReference,为空时显示默认文本
cell.cellCategory.text = searchApi.dataFromSearchApi[indexPath.row].photos.first?.photoReference ?? "无照片"

如果需要遍历所有照片,可使用循环:

let photos = searchApi.dataFromSearchApi[indexPath.row].photos
for photo in photos {
    print(photo.photoReference)
}

2. 添加字段名映射(关键)

给Photo结构体添加CodingKeys枚举,实现JSON字段名与结构体属性名的映射,否则photoReference无法正确解码:

struct Photo: Codable {
    let photoReference: String
    
    enum CodingKeys: String, CodingKey {
        case photoReference = "photo_reference"
    }
}

如果允许部分POI没有照片,建议将属性改为可选类型:

struct Photo: Codable {
    let photoReference: String?
    
    enum CodingKeys: String, CodingKey {
        case photoReference = "photo_reference"
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:03:30