问题描述
说明:我想从下面的响应中访问 Red 值:
"data": {
"id": "193","rootUserId": 359,"profileId": 870,"name": "flowers","unit": "Kilo-Gram","tags": [],"media": "https://onebusinessqrcode.s3.us-east-2.amazonaws.com/e16060cc-9b68-5415-a68c-3880ea16074a.jpg","createdAt": "2021-02-24T12:00:09.534Z","updatedAt": "2021-02-24T12:00:09.534Z","properties": [
{
"Jasmin": [
{
"id": "eb0362a1-231b-4f12-bf10-fb6fcb07f4c1","value": "Red"
}
]
}
]
}
在我的应用程序中,我必须显示响应中的“Jasmin”键,所以我输入了:
let json = try JSONSerialization.jsonObject(with: data,options: .allowFragments) as? NSDictionary
if let data = json?["data"] as? [String:Any] {
if let properties = data["properties"] as? [[String:Any]] {
for property in properties {
var object = CategoriesName()
if let propertyName = property.first?.key {
object.name = propertyName
let value = properties.first?.values
object.value = value!
self.categoryName.append(object)
}
}
}
我已成功获得密钥..但我无法获得(此密钥的“id”或“值”的正确值 -> Jasmin),因为当我打印 Jasmin Key 的值时,它给了我以下信息..我想获得其中任何一个:(我真正需要的是获取/打印值对象的值,例如:-> 特定键的红色-> Jasmin)
[<__nssingleobjectarrayi>( { id = "eb0362a1-231b-4f12-bf10-fb6fcb07f4c1"; value = Red; }) ]
我的结构是:
struct CategoriesName {
var name : String?
var value: Dictionary<String,Any>.Values?
}
用于获取数据的变量:
// Received Category Id
var category_id : String?
var categoryName = [CategoriesName]()
获取数据的整个请求:
func loadCategoriesName(){
var urlBuilder = URLComponents(string: "https://api.yoogad.com/rest/api/v1/profile/store/category/keys")
urlBuilder?.queryItems = [
URLQueryItem(name: "categoryId",value:"\(category_id!)")
]
guard let url = urlBuilder?.url else { return }
var request = URLRequest(url: url)
let token = UserDefaults.standard.value(forKey: "token") as? String ?? ""
request.setValue(token,forHTTPHeaderField: "x-auth-token")
// send request
URLSession.shared.dataTask(with: request) { (data,response,error) in
dispatchQueue.main.async {
// error occured
if error != nil {
Helper().showAlert(title: "Server Error",message: error!.localizedDescription,in: self)
return
}
do {
// access data - safe mode
guard let data = data else {
Helper().showAlert(title: "Data Error",in: self)
return
}
// converting data to JSON
let json = try JSONSerialization.jsonObject(with: data,options: .allowFragments) as? NSDictionary
if let data = json?["data"] as? [String:Any] {
if let properties = data["properties"] as? [[String:Any]] {
for property in properties {
var object = CategoriesName()
if let propertyName = property.first?.key {
object.name = propertyName
let value = properties.first?.values
object.value = value!
self.categoryName.append(object)
}
}
}
}
} catch {
Helper().showAlert(title: "JSON Error",message: error.localizedDescription,in: self)
return
}
self.pickerView.reloadComponent(0)
}
}.resume()
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)