realmasse
realmasse

Reputation: 523

add json string escape characters

let params = [["_event": "bulk-subscribe", "tzID":8, "message":"pid-1175152:"]]
let jParams = try! JSONSerialization.data(withJSONObject: params, options: [])
var jsonString:String = String.init(data: jParams, encoding: .utf8) ?? "err"

The result of the code is to get the following values

[{"_event":"bulk-subscribe","tzID":8,"message":"pid-1175152:"}]

The result I want is the following values. Result value with " added

["{"_event":"bulk-subscribe","tzID":8,"message":"pid-1175152:"}"]

What do I need to fix? Thank you

Upvotes: 0

Views: 734

Answers (1)

vadian
vadian

Reputation: 285079

Your requested output is an array containing one element, a serialized JSON dictionary.

You get this by creating params as a dictionary

let params : [String:Any] = ["_event": "bulk-subscribe", "tzID":8, "message":"pid-1175152:"]

and wrap the result of the serialization in square brackets. There are no escape characters involved.

let jParams = try! JSONSerialization.data(withJSONObject: params)
let jsonStringArray = [String(data: jParams, encoding: .utf8)!]

Upvotes: 1

Related Questions