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

如何使用Swift 4的Decodable协议解析Google自定义搜索API?

使用Swift 4的Decodable协议解析Google自定义搜索API返回的Metatags数据

刚好我之前处理过类似的场景,Google自定义搜索API返回的metatags里的键都是像og:url这种带特殊符号的,直接用Swift属性名肯定不行,得靠Decodable的CodingKeys来做映射,下面给你一步步来:

第一步:创建对应的数据模型

首先我们要为metatags数组里的每个对象创建一个结构体,把JSON里的字段映射成合法的Swift属性名:

struct Metatag: Decodable {
    let ogUrl: String?
    let articleAuthor: String?
    let ogImageHeight: String?
    let ogDescription: String?
    let ogImageWidth: String?
    let ogImage: String?
    
    // 自定义CodingKeys来映射JSON里带特殊符号的键
    enum CodingKeys: String, CodingKey {
        case ogUrl = "og:url"
        case articleAuthor = "article:author"
        case ogImageHeight = "og:image:height"
        case ogDescription = "og:description"
        case ogImageWidth = "og:image:width"
        case ogImage = "og:image"
    }
}

这里要注意,把JSON里的og:url映射成Swift里的ogUrl(小驼峰命名更符合Swift规范),而且因为API返回的字段可能不是必选的,所以属性都设成可选类型String?避免解析失败。

第二步:定义上层数据结构

如果你的完整API返回里还有其他字段(比如包含metatags的items数组),还需要创建上层的模型,比如:

struct SearchItem: Decodable {
    let metatags: [Metatag]?
    // 其他字段比如title、link等也可以在这里按需添加
}

struct SearchResponse: Decodable {
    let items: [SearchItem]?
}

第三步:执行解析操作

拿到API返回的Data之后,用JSONDecoder来解析就可以了:

// 假设你已经通过网络请求拿到了返回的data
do {
    let decoder = JSONDecoder()
    let searchResponse = try decoder.decode(SearchResponse.self, from: data)
    
    // 取出第一个搜索结果的metatags示例
    if let firstItem = searchResponse.items?.first, let firstMetatag = firstItem.metatags?.first {
        print("文章链接:\(firstMetatag.ogUrl ?? "未获取到")")
        print("作者主页:\(firstMetatag.articleAuthor ?? "未获取到")")
        print("文章描述:\(firstMetatag.ogDescription ?? "未获取到")")
    }
} catch {
    print("解析失败:\(error.localizedDescription)")
    // 想排查具体问题的话,可以直接打印error看详细信息
    // print(error)
}

一些额外提示

  • 如果metatags里还有其他你需要的字段,只需要在Metatag结构体里添加对应的属性和CodingKeys映射就行
  • 要是像og:image:height这种实际是数值的字段,你可以把属性类型改成Int?,JSONDecoder会自动帮你完成类型转换
  • 解析失败时,直接打印完整的error对象,能看到具体是哪个字段不匹配,方便快速排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:11:46