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

如何使用SwiftyJSON解析无前置键的JSON数组?

解决SwiftyJSON解析无前置键JSON数组的问题

我明白你遇到的困扰——服务器直接返回了没有外层键的JSON数组,而你现有的解析逻辑可能是针对带键对象编写的,导致没法正确解析。别担心,用SwiftyJSON完全能搞定这个场景,下面是具体的解决方案:

第一步:定义适配SwiftyJSON的Country模型

首先给Country结构体添加一个接收JSON对象的构造器,让每个数组元素都能直接转换成Country实例:

import SwiftyJSON

struct Country {
    let countryID: Int
    let name: String
    let code: String
    let createdDate: String
    
    init?(json: JSON) {
        // 用可选绑定确保必要字段存在,避免崩溃
        guard let id = json["CountryID"].int,
              let countryName = json["Name"].string,
              let countryCode = json["Code"].string,
              let date = json["CreatedDate"].string else {
            return nil
        }
        
        self.countryID = id
        self.name = countryName
        self.code = countryCode
        self.createdDate = date
    }
}

第二步:直接解析顶层JSON数组

因为服务器返回的是顶层数组,SwiftyJSON解析后得到的JSON对象本身就是数组类型,我们不需要去获取某个键对应的值,直接遍历这个JSON对象即可:

// 假设你已经从服务器拿到了响应数据data
do {
    let responseJSON = try JSON(data: data)
    
    var countries: [Country] = []
    // 遍历JSON数组,每个元素都是单个国家的JSON对象
    for (_, countryJSON) in responseJSON {
        if let country = Country(json: countryJSON) {
            countries.append(country)
        }
    }
    
    // 现在countries就是解析完成的国家列表了
    print("成功解析出 \(countries.count) 个国家")
} catch {
    print("JSON解析失败:\(error.localizedDescription)")
}

如果你需要保留CountryList类

如果你还是想用CountryList来包装数组,可以给它也加一个对应的构造器:

struct CountryList {
    let countries: [Country]
    
    init?(json: JSON) {
        var tempCountries: [Country] = []
        for (_, countryJSON) in json {
            if let country = Country(json: countryJSON) {
                tempCountries.append(country)
            }
        }
        self.countries = tempCountries
    }
}

// 使用方式
do {
    let responseJSON = try JSON(data: data)
    if let countryList = CountryList(json: responseJSON) {
        // 在这里使用countryList.countries
    }
} catch {
    // 处理解析错误
}

额外提示

  • 如果需要把CreatedDate转换成Date类型,可以在Country的构造器里加入DateFormatter的解析逻辑;
  • 建议在构造器里做字段校验,避免服务器返回字段缺失导致的崩溃;
  • 确保你的SwiftyJSON是最新版本,避免版本兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:52:29