我正在尝试使用swift 4将以0开头的整数编码为JSON。
我正在使用一个非常标准的JSONSerialization库,但是由于某些原因,在使用utf8将字符串转换为数据后,我无法对其进行序列化。
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)
当前,代码在倒数第二行(以let jsonArray开头)中断并返回nil。请注意,如果我将代码更改为“ 112345”,则不会出现错误。感谢您的任何帮助,谢谢!
答案 0 :(得分:1)
使用Dictionary
和JSONSerialization
来创建data
,而不是手动创建字符串,如下所示,
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)
}
输出
{“代码”:“ 012345”}