【问题标题】:How to Fetch json value in iOS Swift 4 [duplicate]如何在 iOS Swift 4 中获取 json 值 [重复]
【发布时间】:2018-07-27 05:34:03
【问题描述】:

{ "pages": 1, "posts": [ { "id": 2345, "categories": [], “标签”:[],“作者”:{ “身份证”:1, “蛞蝓”:“管理员”, “网址”:“”, “描述”:“”},“cmets”:[],“custom_fields”:{ “幻灯片模板”:[ “默认” ], “请求状态”:[ “待审核” ], “分支”: [ “B分公司” ], “分配给”: [ “常务董事” ], “类别”: [ “设备” ], “优先”: [ “高的” ] } },

这是我的快速编码 直到“custom_fields”我可以获取值,但之后我不能 请任何人帮助我

let url = NSURL(string: urlForCharts)
     do{
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let data = data {
                if let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
            if let postArray = jsonObj!.value(forKey: "posts") as? NSArray {
               for status in postArray{
                   if let tagsDict = status as? NSDictionary {
                if let tagsArray =  tagsDict.value(forKey: "custom_fields") as? NSArray {

                        for statusArray in tagsArray{

                            if let statusDict = statusArray as? NSDictionary {
                        if let status = statusDict.value(forKey: "request_status") {

                            self.ticketStatus.append((status as? String)!)
                            self.ticketStatus = self.ticketStatus.sorted(by: <)

【问题讨论】:

  • 请参阅重复链接中已接受答案的“解析 JSON 的一些一般注意事项”部分。您将学习如何阅读 JSON 并了解 JSON 字典和 JSON 数组之间的区别。
  • 您可以使用Decodable 协议和自定义struct 来解析JSON,这将使您更轻松地进行操作。一旦你在 Swift 中,使用 Swift 的原生类型。 不要使用 NS 类型

标签: ios json swift4 xcode9


【解决方案1】:

您的 custom_fields 的类型是 Dictionary 而不是 NSArray

"custom_fields": {
                    "slide_template": ["default"],
                    "request_status": ["Pending Review"],
                    "branch": ["Branch B"],
                    "assigned_to": ["Managing Director"],
                    "category": ["Equipment"],
                    "priority": ["High"]
                }

所以应该是这样的:

if let tagsDictionary =  tagsDict.value(forKey: "custom_fields") as? NSDictionary {
   if let slide_template = tagsDictionary.value(forKey: "slide_template") as? NSArray{
   }
   if let request_status = tagsDictionary.value(forKey: "request_status") as? NSArray{
       if let resquestStatus = request_status.first as? String{
         //append this value to your array
       } 
   }
}

【讨论】:

  • 我想将键“request_status”的值附加到我的“ticketStatus”NSArray
  • @user7433921 检查更新的答案。
  • 非常感谢它的工作......
【解决方案2】:

试试这个

if let tagsArray =  tagsDict.value(forKey: "custom_fields") as? NSDictionary {
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多