json - Swift 代码出错不知道该写什么来返回?

标签 json swift swift2 nsurl

我无法找到要返回的内容,试图获取 API,但是 NSURL 链接的输出中没有生成任何信息,事件是硬编码的随机数组..谢谢

 func parse (jsonResult: AnyObject?) {

     if let dictionary = jsonResult as? NSDictionary {

        if let event = dictionary["EVENT_ID"] as? NSDictionary {
           print("Event is \(event)")
           if let eventName = event["EVENT_NAME"] as? NSNumber {
              print ("Event name is \(eventName)")
           }
        }

        if let channel = dictionary["CATEGORY_NAME"] as? [String: AnyObject] {
           print("Channel is \(channel)")
           if let eventName = channel["EVENT_NAME"] as? NSNumber {
              print ("Event name is \(eventName)")
           }
        }

     } else {

         if let array = jsonResult as? NSArray {
            for element in array {
               print(element)
            }
         }

         if let array = jsonResult as? [AnyObject] {
            for element in array {
               print(element)
            }
         }
     }
 }

 parse (["EVENT_ID":["EVENT_NAME" : events ]])
 return ...
}

最佳答案

这只是获取结果返回的示例。我建议使用二维数组。我希望我对你有帮助。

func parse (jsonResult: AnyObject?) ->(Dictionary<String,NSNumber>){

    var myDictionary = [String: NSNumber]()

    if let dictionary = jsonResult as? NSDictionary {

        if let event = dictionary["EVENT_ID"] as? NSDictionary {
            print("Event is \(event)")
            if let eventName = event["EVENT_NAME"] as? NSNumber {
                print ("Event name is \(eventName)")
                myDictionary["key1"] = eventName
            }
        }

        if let channel = dictionary["CATEGORY_NAME"] as? [String: AnyObject] {
            print("Channel is \(channel)")
            if let eventName = channel["EVENT_NAME"] as? NSNumber {
                print ("Event name is \(eventName)")
                myDictionary["key2"] = eventName
            }
        }

    } else {

        if let array = jsonResult as? NSArray {
            for element in array {
                print(element)
                //suppose an array are numbers
                myDictionary[String(element)] = element as? NSNumber
            }
        }

        if let array = jsonResult as? [AnyObject] {
            for element in array {
                print(element)
                //suppose an array are numbers
                myDictionary[String(element)] = element as? NSNumber
            }
        }
    }

    return myDictionary
}

关于json - Swift 代码出错不知道该写什么来返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35793644/

相关文章:

ios - 整个 ios 应用程序的放大 UI

swift2 - “Variable ' xxx ' was never mutated; consider changing to '让' constant”错误

xcode - Xcode 模拟器中的导航栏和标题

c# - DataContractJsonSerializer 可以处理循环引用吗?

javascript 将 JSON 字符串转换为 JSON 对象

c++ - Qt - 带注释的 JSON

ios - 在 Swift 4 中根据 Table View 高度动态调整布局

swift - 如何在不使用 UITextView 的 UILabel 中检测和创建可点击链接

php - Laravel 4 - 将 json 解码为 View

iOS 多个不同宽度的 View /标签