(Payload is not valid JSON) trying to print to free up space in swift

let str = "payload={'channel': '#bottest', 'username': 'garrettogrady', 'text': 'This post is coming from swift.'}"
    let strData = (str as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData

    let url = NSURL(string: "web hook url (leaving it out for privacy reasons")

    var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)

    request.HTTPMethod = "POST"
    request.HTTPBody = strData
    println("printing to slack")
    var error : NSError? = nil
    if let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: &error) {
        let results = NSString(data:data, encoding:NSUTF8StringEncoding)
        println(results)
    }
    else
    {
        println("data invalid")
        println(error)
    }

      

So when I run this code, I am not wrong. But when I print the results it says "Payload is not valid JSON"

+3


source to share


2 answers


Slack expects double quotes on JSON. The result you are getting is from Slack rejecting your JSON as it is currently formed.

Here is some code from my own stuff that allows you to include variable values ​​for different fields, which I believe is your next step.



let channel = "#bottest"
let username = "garrettogrady"
let text = "This post is coming from swift."
let payload = "payload={\"channel\": \"\(channel)\", \"username\": \"\(username!)\", \"text\": \"\(text)\""}"

      

EDIT: This question inspired me to create an object to implement the Slack webhook API. Here's for anyone interested: https://github.com/pfj3/SwiftSlackbots

+3


source


Well this is because your JSON is not valid as indicated in the error message.

In a JSON string, the keys must be inside double quotes; dictionaries are separated by character {}

and arrays with []

. Also, use :

instead of =

.

let str = "{\"payload\":{\"channel\": \"#bottest\", \"username\": \"garrettogrady\"}}"

      

You can check if the JSON string is correct by creating an object with it:



if let strData = (str as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
    var error: NSError?
    if let json = NSJSONSerialization.JSONObjectWithData(strData, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject] {
        println(json)
    }
}

      

The object representation of the JSON content is printed (syntax looks different, of course, don't mix it with JSON syntax or Swift syntax):

["payload": {channel = "#bottest"; username = garrettogrady; }]

Then you are sure that your JSON string is approved for submission because you were able to create an object with it.

+1


source







All Articles