I been stuck at this for far too long. I have to send this array as string: "[{"packageId":"1"}, {"packageId":"1"}, {"packageId":"3"}]"
and so on. The values here are being inserted and can be any integer.
As I cannot declare any variable in format like let pjson = {"packageId":"1"}
so I decided to create a string instead in this way: let pjson = "{"packageId":"1"}"
and using for loop im adding data in some array in following way:
for package in packages {
if let pId = package.packageId {
let pjson = "{"packageId":"(pId)"}"
packageJson.append(pjson as Any)
}
}
After this im getting an array like this:
packageJson = ["{"packageId":"1"}", "{"packageId":"2"}", "{"packageId":"3"}", "{"packageId":"4"}", "{"packageId":"5"}", "{"packageId":"6"}"]
Now I want to convert my packageJson
to this format:
packageJson = [{"packageId":"1"}, {"packageId":"2"}, {"packageId":"3"}, {"packageId":"4"}, {"packageId":"5"}, {"packageId":"6"}]
As you can see, I don’t want array content to be a string type.
So I stored whole array as string and decided to remove those "
like this:
var stringJson = "(packageJson)"
stringJson = stringJson.replacingOccurrences(of: "\{", with: "{", options: NSString.CompareOptions.literal, range: nil)
stringJson = stringJson.replacingOccurrences(of: "}\", with: "}", options: NSString.CompareOptions.literal, range: nil)
I tried to ""{"
but got error so using "\{"
as I read somewhere it can be used for "
however that answer wasn’t market correct so not sure.
How can I remove those "
to convert array into my required format? Or is there any better way to declare let pjson = "{"packageId":"(pId)"}"
so I can simply add that without having to use string format? Swift doesn’t allow to start a variable with "{" tho.
Anyway I would just like to get final result in this way:
stringJson = "[{"packageId":"1"}, {"packageId":"2"}, {"packageId":"3"}, {"packageId":"4"}, {"packageId":"5"}, {"packageId":"6"}]"
2
Answers
Your final result is a JSON string of an array of custom objects. There is a way more simpler way to achieve what you want.
First create a struct to hold your values:
Then create you data as you deem fit. Example:
Then encode them with JSONEncoder:
This will give you a
Data
object. You can treat it as string if you like or send it in the body of a datarequest.Example:
will produce:
In Swift 5.0+
you will get the results:
[{"packageId":"1"},{"packageId":"2"}]