如何在Vapor 1.5中遍历JSON对象并将其转换为[String:Any]?

时间:2018-08-10 20:32:35

标签: arrays swift vapor

我正在通过Alamofire将请求发送到我的蒸气1.5服务器,其主体类型为[String:Any],其中Any类型是String:String的字典

在服务器上收到请求后,我将其转换为JSON类型

 guard let reqJson = request.json else {return}

如何遍历此JSON对象并将其转换为[String:Any]的数组

我从客户端应用发送的请求的内容如下:

 ["DHSKL3920JFLSKXFgs": 
   ["title": “some title”, 
    "body": “some body”, 
    "DHSKL3920JFLSKXFgs": "DHSKL3920JFLSKXFgs", 
    "unreadMessagesCount": 3], 

 "PKF993AVG59gkCM": 
   ["title": “some title”, 
    "body": “some body”,  
    "DHSKL39": "DHSKL39", 
     "unreadMessagesCount": 3]] 

3 个答案:

答案 0 :(得分:1)

您可以使用swift4 Codable并将代码缩小到4-5行。 Documentation

答案 1 :(得分:1)

如果我对您的理解正确。也许以下方法会有所帮助。

//This method uses high order function map
func convert(json:[String:Any]) -> [[String: Any]] {
    let requiredObjects = json.map { $0.value as! [String:Any] } //force unwrapping
    return requiredObjects
}

//This method uses simple loop
func convert(json:[String:Any]) -> [[String: Any]] {
    var requiredObjects = [[String:Any]]()
    for (key, value) in json.enumerated() {
        requiredObjects.append([value.key : value.value])
    }
    return requiredObjects
}

答案 2 :(得分:0)

struct DataFromClientSendNotifications {

 let title: String
 let body: String
 let sound: String
 let badge: String
 let fcmToken: String
 let unreadMessagesCount: String

}


    guard let reqJson = request.json else {
      throw Abort.custom(status: .badRequest, message: message)
    }

   for obj in reqJson.object! {

        print("new obj is \(obj)")
        let objKey = obj.key
        let objValue = obj.value.object

        print("objectValue here is \(objValue)")

        let title =  objValue?["title"]?.string
        let body = objValue?["body"]?.string
        let unreadMessagesCount = objValue?["unreadMessagesCount"]?.string
        let sound = objValue?["sound"]?.string
        let badge = objValue?["badge"]?.string
        let fcmToken = objValue?["objValue"]?.string

         let itemCompleted = DataFromClientSendNotifications(title: title!, body: body!, sound: sound!, badge: badge!, fcmToken: fcmToken!, unreadMessagesCount: unreadMessagesCount!)

        print("itemCompleted is \(itemCompleted)")
        //now you can do whatever you want with  itemCompleted

    }