1

Any suggestions in how to parse AWSTask.result into JSON object? I am invoking AWS Lambda function, which returns a JSON string

code below

let task = lambdaInvoker.invokeFunction("LambdaFunction", jsonObject: ["processName":processName])

 task.continue({ (task: AWSTask!) -> AWSTask<AnyObject>! in

        if (task.error != nil) {
            NSLog("Invoke Lambda returned an error : \(task.error)")
            //NSLog("Invoke Lambda returned an error : \(task.error)")

        } else {
            if (task.result != nil) {
                //NSLog("Invoke Lambda : result = \(task.result)")
                var data = task.result as! NSDictionary 

                let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) //THIS WONT WORK, throws error that it cant cast to NSDictionary

                print("responseJSON = \(responseJSON)")



            } else {
                NSLog("Invoke Lambda : unknow result : \(task)");
                NSLog("Exception : \(task.exception)")
                NSLog("Error : \(task.error)" )
                }
        }
        return nil

Any recommendations to parse this to a JSON object so that I can extract specific attributes of the response/result?

Vasu Seshadri
  • 31
  • 1
  • 2

2 Answers2

0

You should cast to NSDictionary after serializing the data, not before.

var data = task.result

let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
Papershine
  • 4,995
  • 2
  • 24
  • 48
  • When I do this, I am getting a `Cannot invoke 'jsonObject' with an argument list of type '(with: SampleResponse?, options: [Any])'` error, where SampleResponse is the Gateway generated class in sdk. – Nagendra Rao Feb 13 '18 at 13:08
  • @Rao without showing the class `SampleResponse`, it will be hard to solve your problem. Your problem should be different from this OP. – Papershine Feb 14 '18 at 00:43
0

I used SwiftyJSON for the parsing: Install it using cocoa pods - https://cocoapods.org

import it in your class where you want to parse

import SwiftyJSON

replace the value of resonseJSON with:

let responseJSON = JSON(task.result)
Sharmin Khan
  • 177
  • 2
  • 13