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

Swift环境下无法从JSON数据中获取room_type_info的技术求助

嘿,我来帮你搞定在Swift里访问JSON的room_type_info字段的问题!下面给你两种常用的解决方案,都是Swift里靠谱的做法:

方法一:用Swift Codable协议(推荐)

这是苹果官方推荐的JSON解析方式,类型安全、代码整洁,适合长期维护的项目。首先你需要根据JSON结构定义对应的模型,把room_type_info字段包含进去:

// 先定义RoomTypeInfo的模型,根据实际JSON里的字段调整
struct RoomTypeInfo: Codable {
    let type: String?
    let description: String?
    let maxOccupancy: Int?
    // 其他你需要的字段,比如设施、价格等,完全匹配JSON结构即可
}

// 其他嵌套结构的模型
struct Contact: Codable {
    let type: String
    let detail: String
}

struct TotalPrice: Codable {
    let amount: String
    let currency: String
}

struct MinDailyRate: Codable {
    let amount: String
    let currency: String
}

struct Address: Codable {
    let line1: String
    let city: String
    let region: String
    let postalCode: String
    let country: String
    
    // 处理JSON里的蛇形命名(比如postal_code)
    enum CodingKeys: String, CodingKey {
        case line1, city, region, country
        case postalCode = "postal_code"
    }
}

struct Location: Codable {
    let latitude: Double
    let longitude: Double
}

// 主模型,包含你要的room_type_info
struct Property: Codable {
    let propertyCode: String
    let propertyName: String
    let location: Location
    let address: Address
    let totalPrice: TotalPrice
    let minDailyRate: MinDailyRate
    let contacts: [Contact]
    let roomTypeInfo: RoomTypeInfo? // 设为可选,避免无此字段时解析失败
    
    enum CodingKeys: String, CodingKey {
        case propertyCode = "property_code"
        case propertyName = "property_name"
        case location, address, totalPrice = "total_price"
        case minDailyRate = "min_daily_rate"
        case contacts, roomTypeInfo = "room_type_info"
    }
}

然后就可以解析并访问room_type_info了:

// 假设你已经有了JSON数据(比如网络请求返回的Data)
if let jsonData = yourJsonString.data(using: .utf8) {
    do {
        let decoder = JSONDecoder()
        // 如果JSON有日期等特殊格式,可在这里配置decoder
        let properties = try decoder.decode([Property].self, from: jsonData)
        
        // 遍历结果数组,访问每个酒店的room_type_info
        for property in properties {
            if let roomInfo = property.roomTypeInfo {
                print("房间类型:\(roomInfo.type ?? "未知")")
                print("房间描述:\(roomInfo.description ?? "无描述")")
                // 按需访问其他字段
            } else {
                print("该酒店未提供房间类型信息")
            }
        }
    } catch {
        print("解析失败:\(error.localizedDescription)")
    }
}
方法二:手动解析(JSONSerialization)

如果只是临时调试或者JSON结构简单,也可以用手动解析的方式,灵活性更高但类型安全稍差:

// 同样假设你有JSON Data
if let jsonData = yourJsonString.data(using: .utf8) {
    do {
        // 把Data转成JSON对象
        guard let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any],
              let results = jsonObject["results"] as? [[String: Any]] else {
            print("JSON结构不符合预期")
            return
        }
        
        // 遍历结果数组
        for property in results {
            // 取出room_type_info字段
            if let roomTypeInfo = property["room_type_info"] as? [String: Any] {
                // 访问里面的具体字段,注意类型转换
                let roomType = roomTypeInfo["type"] as? String ?? "未知"
                let roomDesc = roomTypeInfo["description"] as? String ?? "无描述"
                print("房间类型:\(roomType)")
                print("房间描述:\(roomDesc)")
                // 其他字段同理,按需转换类型
            } else {
                print("未找到room_type_info字段")
            }
        }
    } catch {
        print("解析失败:\(error.localizedDescription)")
    }
}

注意事项

  • 确保你的JSON结构里确实存在room_type_info字段,如果它嵌套在更深的层级(比如某个房间数组里),要调整模型或手动解析的层级路径。
  • 如果room_type_info是数组而非字典,模型里要改成[RoomTypeInfo]?,手动解析时也要转成[[String: Any]]。
  • Codable模式下,一定要保证CodingKeys和JSON的键完全对应,蛇形命名的映射不能出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:05:31