我无法将 json 值放入变量中。我正在打印值,但问题是我无法在没有数组的情况下获取 json 值
这是我的 json
{
"Categories": [
"city",
"delhi"
]
}
我想用数组对值进行分类,并用数组打印值
这是我的代码
do{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
print(json as AnyObject)
if let Categories = json["Categories"] {
print(Categories)
}
最佳答案
你需要
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:[String]]
let arr1 = json["Categories"]!
let str1 = arr1.joined(separator: ":")
print(str1)
// or
let decoded = try JSONDecoder().decode(Root.self, from: data)
let str = decoded.categories.joined(separator: ":")
print(str)
} catch {
print(error)
}
或使用
struct Root: Codable {
let categories: [String]
enum CodingKeys: String, CodingKey {
case categories = "Categories"
}
}
关于ios - 如何在swift4中从json数组获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55004044/