gpt4 book ai didi

json - 在 Swift 中将可选元素附加到 json 数组中

转载 作者:行者123 更新时间:2023-11-30 11:54:04 25 4
gpt4 key购买 nike

我刚刚开始熟悉 JSON。我有一个类对象,我通过传入 JSON 来初始化它。该对象有一个可能为空的数组,我需要检查它的值。到目前为止我正在尝试:

    init(json: JSON) {
id = json["id"].string
type = json["type"].string
text = json["text"].string
answer = json["answer"].string
format = json["format"].string
answeredBy = []

if let answeredByjson = json["answeredBy"].array {
for (_, userDict) in answeredByjson {
if let userDict = userDict as? [String : Any] {
answeredBy.append(JSON(User(dictionary: userDict)))
}
}
}
}

数组中的元素是必须用于初始化另一个对象(用户)的字典。我收到的错误是:

Expression type '[JSON]' is ambiguous without more context.

如何更新我的代码?

这是我的 json:

    {        
"answer" : "rachel",
"answeredBy" : {
"j1K4WXbOFRXfm3srk9oMtZJ8Iop2" : {
"email" : "an email",
"pictureURL" : "a URL",
"uid" : "j1K4WXbOFRXfm3srk9oMtZJ8Iop2",
"name" : "a name"
},
"vtYlmyerugedizHyOW6TV847Be23" : {
"email" : "an email",
"pictureURL" : "a URL",
"uid" : "vtYlmyerugedizHyOW6TV847Be23",
"name" : "Rusty Shakleford"
}
},
"format" : "field",
"id" : "1",
"type" : "text",
"text" : "In a foot race, Jerry was neither first nor last. Janet beat Jerry, Jerry beat Pat. Charlie was neither first nor last. Charlie beat Rachel. Pat beat Charlie. Who came in last?"
}

最佳答案

if let answeredByjson = json["answeredBy"].array {
...
}

生成一个数组[JSON],但您希望它生成一个字典[String: JSON]。这就是为什么您会收到:

Expression type '[JSON]' is ambiguous without more context

生成字典:

if let answeredByjson = json["answeredBy"].dictionary {
...
}

如果您不希望它生成字典[String: JSON],那么这一行就没有意义

for (_, userDict) in answeredByjson {

关于json - 在 Swift 中将可选元素附加到 json 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com