[英]Unable to get value from JSON array of dictionaries in swift
json response: "result": { json 响应:“结果”:{
"user_images": [
{
"id": 113,
"user_id": "160",
"image": "1617349564.jpg",
"image_title": "33"
},
{
"id": 112,
"user_id": "160",
"image": "1617349541.jpg",
"image_title": "22"
},
{
"id": 111,
"user_id": "160",
"image": "1617349528.jpg",
"image_title": "11"
},
........
code : with this code i am getting response like above means all user_images
array coming... but here i need image_title
how to get that .. if i run for loop getting error.. pls do help代码:使用此代码,我得到像上面这样的响应意味着所有user_images
数组都来了...但是在这里我需要image_title
如何获得它..如果我运行 for loop 得到错误..请帮忙
if let code = ((response.dict?["result"] as? [String : Any])){
let userImages = code["user_images"] as? [String : Any]
}
how to get image_title
value from above array of dictionaries如何从上面的字典数组中获取image_title
值
Sol 1溶胶一
if let code = response.dict?["result"] as? [String : Any] {
if let userImages = code["user_images"] as? [[String : Any]] {
for item in userImages {
print(item["image_title"])
}
}
}
Sol 2溶胶 2
if let code = response.dict?["result"] as? [String : Any] {
do {
let data = try JSONSerialization.data(withJSONObject: code)
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let res = try decoder.decode(Result.self, from: data)
let titles = res.userImages.map { $0.imageTitle }
print(titles)
}
catch {
print(error)
}
}
// MARK: - Result
struct Result: Codable {
let userImages: [UserImage]
}
// MARK: - UserImage
struct UserImage: Codable {
let id: Int
let userId, image, imageTitle: String
}
if let code = response.dict?["result"] as? [String : Any] {
//You're using "as?" which means you're casting as an optional type.
//One simple solution to this is here where it's unwrapped using "if let"
if let userImages = code["user_images"] as? [[String : Any]] {
// [String:Any] is a Dictionary
// [[String:Any]] is an Array of Dictionary
for item in userImages {
print(item["image_title"])
}
} else {
// We didn't unwrap this safely at all, do something else.
}
Let's dive into this a little bit.让我们深入研究一下。 This structure is a JSON Object这个结构是 JSON Object
{
"id": 113,
"user_id": "160",
"image": "1617349564.jpg",
"image_title": "33"
}
But it's only a JSON object when it stands alone.但是当它独立时,它只是一个 JSON object。 Adding a key, or in this example user_images
makes it a dictionary.添加一个键,或者在这个例子中user_images
使它成为一个字典。 Notice that the [
is not wrapped around it.请注意, [
没有包裹它。 Meaning it's a standalone dictionary.意味着它是一个独立的字典。 If this was your object, and this alone, your original code would work, but you're dealing with an Array
of Dictionaries
.如果这是您的 object,仅此一项,您的原始代码就可以工作,但您正在处理一个Array
of Dictionaries
。
"user_images":
{
"id": 113,
"user_id": "160",
"image": "1617349564.jpg",
"image_title": "33"
}
This line of code essentially means that you're expecting to get back that Array
of Dictionary
.这行代码本质上意味着您期望取回该Array
of Dictionary
。 Bear in mind, each value for the dictionary is not an array value, which is why you don't see something like this [[[String: Any]]]
because the data isn't nested like that.请记住,字典的每个值都不是数组值,这就是为什么您看不到类似[[[String: Any]]]
的内容,因为数据不是这样嵌套的。
if let userImages = code["user_images"] as? [[String : Any]]
An optional is basically a nil
possible value that can be returned.可选项基本上是可以返回的nil
可能值。 Typically when working with JSON you cannot guarantee that you'll always receive a value for a given key.通常,在使用 JSON 时,您不能保证始终会收到给定键的值。 It's even possible for a key value pair to be completely missing.键值对甚至可能完全丢失。 If that were to happen you'd end up with a crash, because it's not handled.如果发生这种情况,您最终会崩溃,因为它没有得到处理。 Here are the most common ways to handle Optionals
以下是处理Optionals
的最常用方法
var someString: String? //This is the optional one
var someOtherString = "Hello, World!" //Non-optional
if let unwrappedString1 = someString {
//This code will never be reached
} else {
//This code will, because it can't be unwrapped.
}
guard let unwrappedString2 = someString else {
//This code block will run
return //Could also be continue, break, or return someValue
}
//The code will never make it here.
print(someOtherString)
Furthermore, you can work with optionals by chain unwrapping them which is a nifty feature.此外,您可以通过链式展开来使用选项,这是一个很好的功能。
var someString: String?
var someInt: Int?
var someBool: Bool?
someString = "Hello, World!"
//someString is not nil, but an important distinction to make, if any
//fail, ALL fail.
if let safeString = someString,
let safeInt = someInt,
let safeBool = someBool {
//If the values are unwrapped safely, they will be accessible here.
//In this case, they are nil, so this block will never be hit.
//I make this point because of scope, the guard statement saves you from the
//scoping issue present in if let unwrapping.
print(safeString)
print(safeInt)
print(safeBool)
}
guard let safeString = someString,
let safeInt = someInt,
let safeBool = someBool {
//This will be hit if a value is null
return
}
//However notice the scope is available outside of the guard statement,
//meaning you can safely use the values now without them being contained
//to an if statement. Despite this example, they would never be hit.
print(safeString)
print(safeInt)
print(safeBool)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.