ios - 如何将 JSON 中的值附加到数组?

标签 ios json swift

我正在尝试从 JSON 获取值并将它们附加到 titleArray

func updateUI() {
        DispatchQueue.global(qos: .background).async {
            // network call to the API
            self.fetchTipsJson(completion: { (res) in
                switch res {
                case .success(let tips):
                     self.titleArray.append(tips.responseList!.values[title]) // Cannot subscript a value of type '[Value]' with an index of type 'String?'
                    print(self.titleArray)

                case .failure(let err):
                    print("Failed to fetch tips:", err)
                }

            })
            DispatchQueue.main.async {
                // Update the UI Label here

            }
        }
    }

我收到错误,但我认为这不是应该做的事情。

JSON:

{
    "$type": "DTOMapper.DTOResponseList`1[[Telemed.Dto.DTOTip, Telemed.Dto]], DTOMapper",
    "ResponseList": {
        "$type": "System.Collections.Generic.List`1[[Telemed.Dto.DTOTip, Telemed.Dto]], mscorlib",
        "$values": [
            {
                "$type": "Telemed.Dto.DTOTip, Telemed.Dto",
                "Title": "NO TE JUNTES CON LUQUITAS",
                "Text": "Porque si tenes un amigo lucas y otro amigo lucas, tenés dos lucas. Pero no te sirven para pagar nada",
                "GroupName": "TGC.Tips1",
                "ConfigurationPath": "TelemedGlobalConfig>Tips>Tips[0]"
            },
            {
                "$type": "Telemed.Dto.DTOTip, Telemed.Dto",
                "Title": "no te emborraches en las fiestas",
                "Text": "Terminarás pateando globos",
                "GroupName": "TGC.Tips2",
                "ConfigurationPath": "TelemedGlobalConfig>Tips>Tips[1]"
            }
        ]
    },
    "StatusCode": 200,
    "ErrorId": 0
}

我是否正确访问了$values?如果有帮助,titleArray 将与 UILabel 一起使用。

编辑updateLabels():

func updateLabels() {
        self.myTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { (t) in
            self.titleLabel.text = self.titleArray[self.counter] as? String
            self.textLabel.text = self.textArray[self.counter] as? String
            self.counter += 1
            if self.counter == self.titleArray.count && self.counter == self.textArray.count{
                t.invalidate()
            }
        }
    }

编辑回调:

do {
            let tips = try JSONDecoder().decode(Root.self, from: data!)
            self.titleArray = tips.responseList!.values.map { $0.title }
            self.textArray = tips.responseList!.values.map { $0.text }
            DispatchQueue.main.async {
                self.updateLabels()
            }
            completion(.success(tips))
        } catch let jsonError {
            completion(.failure(jsonError))
        }

编辑viewDidLoad():

override func viewDidLoad() {
        super.viewDidLoad()

        fetchTipsJson { (res) in
            switch res {
            case .success:
                return
            case .failure(let err):
                print("Failed to fetch tips:", err)
            }
        }
    }

最佳答案

values 是一个数组而不是字典,您需要将其映射到 title 字符串,所以请尝试

let str = """

{
"$type": "DTOMapper.DTOResponseList`1[[Telemed.Dto.DTOTip, Telemed.Dto]], DTOMapper",
"ResponseList": {
"$type": "System.Collections.Generic.List`1[[Telemed.Dto.DTOTip, Telemed.Dto]], mscorlib",
"$values": [
{
"$type": "Telemed.Dto.DTOTip, Telemed.Dto",
"Title": "NO TE JUNTES CON LUQUITAS",
"Text": "Porque si tenes un amigo lucas y otro amigo lucas, tenés dos lucas. Pero no te sirven para pagar nada",
"GroupName": "TGC.Tips1",
"ConfigurationPath": "TelemedGlobalConfig>Tips>Tips[0]"
},
{
"$type": "Telemed.Dto.DTOTip, Telemed.Dto",
"Title": "no te emborraches en las fiestas",
"Text": "Terminarás pateando globos",
"GroupName": "TGC.Tips2",
"ConfigurationPath": "TelemedGlobalConfig>Tips>Tips[1]"
}
]
},
"StatusCode": 200,
"ErrorId": 0
}
"""



do {
      let res = try JSONDecoder().decode(Root.self, from: Data(str.utf8))
      let arr = res.responseList.values.map { $0.title }
      print(arr)
   }
   catch {
        print(error)
    }
}
<小时/>
// MARK: - Empty
struct Root: Codable {
    let type: String
    let responseList: ResponseList
    let statusCode, errorID: Int

    enum CodingKeys: String, CodingKey {
        case type = "$type"
        case responseList = "ResponseList"
        case statusCode = "StatusCode"
        case errorID = "ErrorId"
    }
}

// MARK: - ResponseList
struct ResponseList: Codable {
    let type: String
    let values: [Value]

    enum CodingKeys: String, CodingKey {
        case type = "$type"
        case values = "$values"
    }
}

// MARK: - Value
struct Value: Codable {
    let type, title, text, groupName: String
    let configurationPath: String

    enum CodingKeys: String, CodingKey {
        case type = "$type"
        case title = "Title"
        case text = "Text"
        case groupName = "GroupName"
        case configurationPath = "ConfigurationPath"
    }
}
<小时/>

编辑:

var counter = 0

var myTimer:Timer!

self.myTimer =    Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { (t) in
    self.lbl.text = self.titleArr[self.counter]
    counter += 1
    if self.counter == self.titleArr.count {
        t.invalidate()
    }
}

关于ios - 如何将 JSON 中的值附加到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56581319/

相关文章:

ios - 使用 popViewControllerAnimated(true) 导航出 UITableView 时如何修复 UISearchController 的警告

iOS。是否可以覆盖远程 json 文件的内容或将其替换为新文件?

Javascript - 遍历数组并根据其中的键值对对象进行排序

ios - 初始化前使用的变量

swift - 创建并编程一个按钮,该按钮将删除 uitextview 中的最后一个字母

ios - 如何使用 Starscream 修复 "websocket is disconnected: Invalid HTTP upgrade"错误

ios - 快速更改 UIImageView 的位置

iOS - deviceready 5 秒后尚未触发

ios - UICollectionView 仅显示第一项

asp.net-mvc - MVC 将对象的 Json 集合绑定(bind)到 Controller 操作