bibscy
bibscy

Reputation: 2718

How to loop through a JSON object in Vapor 1.5 and convert it to [String:Any]?

I am sending a request to my vapor 1.5 server via Alamofire with body of type [String:Any] where Any type is a dictionary of String:String

When the request is received on the server I convert it to JSON type

 guard let reqJson = request.json else {return}

How can I loop through this JSON object and convert it to an array of [String:Any]

The body of the request I send from the client app looks like this:

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

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

Upvotes: 1

Views: 89

Answers (3)

kathayatnk
kathayatnk

Reputation: 1015

If I understood you correctly. Maybe the following will help.

//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
}

Upvotes: 1

bibscy
bibscy

Reputation: 2718

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

    }

Upvotes: 0

Pouya Kahfi
Pouya Kahfi

Reputation: 53

You can use swift4 Codable and shrink your code to 4-5 lines. Documentation

Upvotes: 1

Related Questions