【问题标题】:Get an Array of Specific Value from the Json Model in Swift从 Swift 中的 Json 模型中获取特定值的数组
【发布时间】:2022-01-10 10:33:18
【问题描述】:

我想要一个仅包含以下 Model Class 中的 userName 的数组:

struct MyModel: Codable {
    let status: Int?
    let message: String?
    let data: [MyModelClass]?
}

struct MyModelClass: Codable {
    let userID, userName, email, emailCode: String?
    let phone, password: String?
    let image: String?
    let dreamInfo: String?

    enum CodingKeys: String, CodingKey {
        case userID = "user_id"
        case userName = "user_name"
        case email
        case emailCode = "email_code"
        case phone, password, image
        case dreamInfo = "dream_info"
    }
} 

我想要一个只有 userNames 的数组。如何快速完成?

我的模型回复如下:

{
    "status": 1,
    "message": "user found ",
    "data": [
        {
            "user_id": "1",
            "user_name": "ali",
            "email": "ali@gmail.com",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        },
        {
            "user_id": "2",
            "user_name": "raza",
            "email": "raza@gmail.com",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        },
        {
            "user_id": "3",
            "user_name": "usman",
            "email": "usman@gmail.com",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        },
        {
            "user_id": "4",
            "user_name": "haroon",
            "email": "haroon@gmail.com",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        }
    ]
}

我只想要这个模型的用户名。这是我想要的输出:

var myArray = ["ali", "raza", "usman", "haroon"]

如果模型类中有 10 个值,那么我需要 myArray 来拥有所有 10 个用户名。

【问题讨论】:

  • 您可以使用 for 循环进行迭代,或者使用像 map() 这样的高方法。你试过什么?请注意,手动执行 for 循环也不错,它是基本算法,稍后将帮助您提高编码技能。 map 是更“Swifty”和更高级别的方法,但如果你不明白它为什么起作用,它可能与你当前的级别无关。
  • 使用:var arr: [MyModelClass] = [] for item in data where item.userName == "raj" { arr.append(item) } debugPrint(arr)
  • @Larme 我正在搜索这方面的内容,并通过 map() 找到了解决方案,但不了解如何实现它。
  • @TaimoorArif map() 在这里无法正常工作,因为它会返回整个数组,但您需要过滤一个。
  • 您想要的是 let userNames = myModel.data?.compactMap(\.userName) 或者如果您将属性设为非可选 let userNames = result.data.map(\.userName)

标签: arrays swift string model


【解决方案1】:

对Kudos答案的简单修改

var arr = []
for item in data {
    arr.append(item.Username)
}
debugPrint(arr)

【讨论】:

  • 你没有得到它。我不想要整个数组,我只想要其中的用户名
  • @TaimoorArif 我已经编辑了我的答案,这解决了吗?
  • 我已经在上面的 cmets 中得到了答案。谢谢
  • 这也不能编译所以不是很有用
  • @Kudos 你最好先理解这个问题。我知道如何编写一个 for 循环,但我没有使用它来获取 name = kudos 的名称,我想要整个数组只有名称
【解决方案2】:

这是工作代码,在操场上测试

import Foundation

let json: String = """
{
    "status": 1,
    "message": "user found ",
    "data": [
        {
            "user_id": "1",
            "user_name": "ali",
            "email": "ali@gmail.com",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        },
        {
            "user_id": "2",
            "user_name": "raza",
            "email": "raza@gmail.com",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        },
        {
            "user_id": "3",
            "user_name": "usman",
            "email": "usman@gmail.com",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        },
        {
            "user_id": "4",
            "user_name": "haroon",
            "email": "haroon@gmail.com",
            "email_code": "0",
            "phone": "0",
            "password": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            "image": "",
            "dream_info": "this is my dream"
        }
    ]
}
"""

struct MyModel: Codable {
    let status: Int?
    let message: String?
    let data: [MyModelClass]?
}

struct MyModelClass: Codable {
    let userID, userName, email, emailCode: String?
    let phone, password: String?
    let image: String?
    let dreamInfo: String?

    enum CodingKeys: String, CodingKey {
        case userID = "user_id"
        case userName = "user_name"
        case email
        case emailCode = "email_code"
        case phone, password, image
        case dreamInfo = "dream_info"
    }

}

func loadJson() {
    
    guard let data = json.data(using: .utf8) else {
        print("Cant convert String to Data")
        return
    }

    
    do {
        let model = try JSONDecoder().decode( MyModel.self, from: data)
        if let data = model.data {
            let array = data.filter({$0.userName != nil}).map({$0.userName!})
            print(array)
        }
    } catch {
        print("Can't convert json to model")
    }
    
}

loadJson()

控制台中的结果:

【讨论】:

  • 谢谢哥们,但我在问题的评论部分得到了答案
猜你喜欢
  • 1970-01-01
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2019-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多