If you can't debug yourself, NEVER USE try?
. With more experience, I'd say that we tend to not use try?
, but sometimes we do. But when we write try?
, we are able to find an possible issue, ie debug if needed.
Let's do a proper try then, with a do/catch:
do {
let data = try JSONEncoder().encode(value)
print(data)
} catch {
print("Error: \(error)")
}
And read the output.
Also, don't output error.localizedDescription
which is more intented for the user, not the developer, output error
.
The output is:
Error: invalidValue("1234567=8+90",
Swift.EncodingError.Context(codingPath: [],
debugDescription: "Top-level String encoded as string JSON fragment.",
underlyingError: nil))
In other words:
A JSON is 99% of the time a Dictionary
or an Array
at top level, in Codable wording, it's a Codable struct with its property or an array of it.
But, some JSON reference allow a simple String
to be JSON valid.
I guess it's been allowed with JSONEncoder
in iOS13+ (see related question)
In iOS, it's a fragment
. The option is available with older JSONSerialization
but not with JSONEncoder
.
let data = JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed])
Now, you can use @available(iOS 13, *)
to call either JSONEncoder
or JSONSerialization
:
if #available(iOS 13.0, *) {
//Do the JSONEncoder thing
} else {
//Do the JSONSerialization Thing
}
Disclaimer:
The start of the answer with the try?
is a copy/paste from another of MY OWN answer. So no plagiarism.