我想使用Swift 5创建一个嵌套的JSON字符串,包含已安装的字体族及其相关字体(稍后我可以将其发送到webview)。
我很难理解Swift嵌套对象。是否有一个特定类型的对象结构需要JSONSerialization?
var obj: [String: Any] = [:]
for family in UIFont.familyNames {
var fonts: [String] = []
for font in UIFont.fontNames(forFamilyName: family) {
fonts.append(font)
}
obj[family] = fonts
}
do {
let json = try JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted)
print(json) // Outputs ‘9415 bytes’ rather than JSON string (below)
} catch {}
我希望JSON字符串看起来像:
{
“Didot”:[“Didot”,”Didot-Italic”,”Didot-Bold”],
“Impact”:[”Impact”],
// etc
}
let string = String(data: json, encoding: .utf8)!
print(string)