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

如何使用struct解析无属性名JSON并访问options数组内的三个元素

解决方案

你当前的问题在于JSON中options数组的元素都是纯字符串类型,没有嵌套的键值结构,不需要额外定义Options结构体来封装。

最简修正代码

直接将options的属性类型改为[String]即可:

struct Atts: Codable {
    let options: [String]
    
    // 如果属性名和JSON的key完全匹配,CodingKeys也可以直接省略
    enum CodingKeys: String, CodingKey {
        case options
    }
}

元素访问方式

解析得到Atts实例后,直接通过下标访问数组元素即可:

// 示例:解析完成后获取三个元素
let firstOption = attsInstance.options[0] // "6GB RAM/128GB"
let secondOption = attsInstance.options[1] // "8GB RAM/128GB"
let thirdOption = attsInstance.options[2] // "12GB RAM/256GB"

如需保留Options结构体的兼容方案

如果业务需要保留Options结构体定义(比如后续要扩展字段),可以调整Options的解码逻辑,适配字符串类型的输入:

struct Options: Codable {
    let rawValue: String
    
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        rawValue = try container.decode(String.self)
    }
}

这种场景下访问元素需要取对应的属性:attsInstance.options[0].rawValue


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:06:05