add json string escape characters - json

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

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)!]

Related

Convert string preceeded with 0 to Json in Swift 4

I'm trying to encode an integer that starts with a 0 into JSON using swift 4.
I'm using a pretty standard JSONSerialization library, but for some reason, after converting the string to data using utf8, I cannot serialize it.
let code = "012345" // example code
let body = "{\"code\": " + code + "}"
let stringData = body.data(using: .utf8)!
let jsonArray = try? JSONSerialization.jsonObject(with: stringData, options : .allowFragments) [returns nil]
let data: Data? = try? JSONSerialization.data(withJSONObject: jsonArray as Any, options: .prettyPrinted)
Currently, the code breaks on the second to last line (starting with let jsonArray) and returns nil. Note that if I were to change code to "112345", there would be no error. Any help is appreciated, thanks!
Instead of manually creating string, use Dictionary and JSONSerialization to create data as below,
let code = "012345"
let body: [String: Any] = ["code": code]
do {
let stringData = try JSONSerialization.data(withJSONObject: body, options: .sortedKeys)
print(String.init(data: stringData, encoding: .utf8)!)
} catch {
print(error)
}
Output
{"code":"012345"}

Create ordered json string to use for key signing

To understand the problem I need to provide some background to what I am trying to achieve.
I am trying to create a JWT with this library that will be signed with a private key.
My problem is that the dictionary that I use to create the JSON is unordered, which therefore results in an unordered JSON string.
The code below prints the JSON string in any order.
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
withJSONObject: dictionary,
options: .prettyPrinted
),
let theJSONText = String(data: theJSONData,
encoding: String.Encoding.ascii) {
print("JSON string = \n\(theJSONText)")
}
let privateKey = theJSONText.data(using: .utf8)
let jwtSigner = JWTSigner.hs256(privateKey: privateKey)
let signedJWT = try myJWT.sign(using: jwtSigner) // This produces a JWT with an invalid signature
The result of this is that my JWT produces an invalid signature. How do I produce a JSON string that has order?
JSONEncoder encodes a dictionary always in the same order (which however might not be the given order of the dictionary). But maybe it fulfills your needs.
if let theJSONData = try? JSONEncoder().encode(dictionary) {
let theJSONText = String(data: theJSONData, encoding: .utf8)!
print("JSON string = \n\(theJSONText)")
}
And there is also the sortedKeys option of OutputFormatting
And – once again – never prettyPrint anything which is going to be sent to a server.

How to json with array and string in swift 3

I want to make json like this.
timings = [{"day":"Monday","from":"01:00pm","to":"04:00pm"},{"day":"Tuesday","from":"01:00pm","to":"04:00pm"}],
The day is array and (from) and (to) is string value.
I use this code.
let myjson = Category.map({ ["": $0] })
Category is array.
let phoneNumbersDictionary = yourArray.map({ ["day": $0 , "to" :txt_timing_to.text! , "from":txt_timing_from.text!] })
let JSON = try? JSONSerialization.data(withJSONObject: phoneNumbersDictionary, options: [])
if let JSON1 = JSON
{
print(String(data: JSON1, encoding: String.Encoding.utf8)!)
}

Alamofire returns invalid url, when building an url from json string

Alamofire returns a invalid URL
I am forming an URL string for Searching (urlStrForCustSearch) using the following code
and URL_CUSTOMER_SEARCH = "http://pos1domain.mobi/pos/SV_IOS.asmx/IosJasonToDatatbl":
let customerJson = [[
"customer_id":nil,
"tel":1234567,
"email":nil,
"addr":nil,
"history":nil]]
do{
let JSONData = try JSONSerialization.data(withJSONObject: customerJson, options: [])
let JSONText = String(data: JSONData,
encoding: .utf8)!
let urlStrForCustSearch = URL_CUSTOMER_SEARCH+"?jsonText=\(JSONText)&funname=GET_MM_CUSTOMER_DTL_LST"
print(urlStrForCustSearch)
Alamofire.request(urlStrForCustSearch, method: .post, parameters: [:], encoding: URLEncoding.default, headers: [:]).responseString { response in
if response.result.isSuccess {
print("Response is success")
}else{
print("Response Failed")
print("Reason : \(response)")
}
}
}catch{
print("Cannot parse the dictionary")
}
Console prints desired url
RightURL:
http://pos1domain.mobi/pos/SV_IOS.asmx/IosJasonToDatatbl?jsonText=[{"tel":1234567,"email":null,"history":null,"customer_id":null,"addr":null}]&funname=GET_MM_CUSTOMER_DTL_LST
but on passing the urlStrForCustSearch string to Alamofire as parameter, Alamofire return invalid URL
Response Failed
Reason : FAILURE: invalidURL("http://pos1domain.mobi/pos/SV_IOS.asmx/IosJasonToDatatbl?jsonText=[{\"tel\":1234567,\"email\":null,\"history\":null,\"customer_id\":null,\"addr\":null}]&funname=GET_MM_CUSTOMER_DTL_LST")
As we can see that '\' is added inside the url string
Can any one help me in creating the url string with out '\' string
Please let me know if any input needed.
Backslashes are used to escape special characters in a string.
If you imagine trying to assign a string variable in Swift which contained double quotes like so:
let str = "They said "hi" when I walked in"
Xcode would show an error here as your string actually ends at "They said " (opened and closed double quotes.
To address the issue you need to escape the double quotes that should be part of the string, like so
let str = "They said \"hi\" when I walked in"
Without this both your code in the iOS project would have issues and your API would have issues reading the string, it would not be valid.
When using special characters in a URL, you can encode the string with Percent Encoding which replaces special characters into a format that browsers can understand. If you convert the full url using percent encoding it is not very readable:
http%3A%2F%2Fpos1domain%2Emobi%2Fpos%2FSV%5FIOS%2Easmx%2FIosJasonToDatatbl%3FjsonText%3D%5B%7B%22tel%22%3A1234567%2C%22email%22%3Anull%2C%22history%22%3Anull%2C%22customer%5Fid%22%3Anull%2C%22addr%22%3Anull%7D%5D%26funname%3DGET%5FMM%5FCUSTOMER%5FDTL%5FLST
So it is usually best to just encode the query string (GET params) of the URL.
let baseUrlString = "http://pos1domain.mobi/pos/SV_IOS.asmx/IosJasonToDatatbl"
let queryString = "?jsonText=[{\"tel\":1234567,\"email\":null,\"history\":null,\"customer_id\":null,\"addr\":null}]&funname=GET_MM_CUSTOMER_DTL_LST".addingPercentEncoding(withAllowedCharacters: .alphanumerics)!
let urlString = baseUrlString + queryString
print(urlString)
Output: http://pos1domain.mobi/pos/SV_IOS.asmx/IosJasonToDatatbl%3FjsonText%3D%5B%7B%22tel%22%3A1234567%2C%22email%22%3Anull%2C%22history%22%3Anull%2C%22customer%5Fid%22%3Anull%2C%22addr%22%3Anull%7D%5D%26funname%3DGET%5FMM%5FCUSTOMER%5FDTL%5FLST
UPDATE - Better Solution
I completely forgot that you are using Alamofire, I was addressing the string issue you mentioned. Alamofire can deal with the encoding for you automatically by passing the parameters into the request call.
let parameters: Parameters = ["foo": "bar"]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default`
Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default)
Thanks Scriptable,
let queryString = JSONText.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!
the above line made the difference and it was ".get" method.
let JSONData = try JSONSerialization.data(withJSONObject: customerJson, options: [])
let JSONText = String(data: JSONData,
encoding: .utf8)!
//Without this line we will get invalid url from alamofire
let queryString = JSONText.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!
let urlStringForCust = URL_CUSTOMER_SEARCH+"?jsonText=\(queryString)&funname=GET_MM_CUSTOMER_DTL_LST"
print(urlStringForCust)
Alamofire.request(urlStringForCust, method: .get, parameters: [:], encoding: URLEncoding.default, headers: [:]).responseString { response in
if response.result.isSuccess {

How to convert dictionary to json string without space and new line

I am trying to convert a dictionary to json string without space and new line. I tried to use JSONSerialization.jsonObject but I still can see spaces and new lines. Is there any way to have a string result looks something like this
"data": "{\"requests\":[{\"image\":{\"source\":{\"imageUri\":\"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png\"}},\"features\":[{\"type\":\"LOGO_DETECTION\",\"maxResults\":1}]}]}"
My conversion
var features = [[String: String]]()
for detection in detections {
features.append(["type": imageDetection[detection]!])
}
let content = ["content": base64Image]
let request = ["image": content, "features": features] as [String : Any]
let requests = ["requests": [request]]
let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: .prettyPrinted)
let decoded = try! JSONSerialization.jsonObject(with: jsonData, options: [])
print(decoded)
Result
{
requests = (
{
features = (
{
type = "LABEL_DETECTION";
},
{
type = "WEB_DETECTION";
},
{
type = "TEXT_DETECTION";
}
);
image = {
content = "iVBO
...........
You are decoding the serialized JSON into an object. When an object is printed into the console, you will see the indentation, and the use of equals symbols and parentheses.
Remove the .prettyPrinted option and use the data to initialize a string with .utf8 encoding.
let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: [])
let decoded = String(data: jsonData!, encoding: .utf8)!