在 Freddy JSON 和 Swift 中,存在一个扩展...
“通过将集合
的每个元素复制到新的数组
中来创建实例”,如下面的 Freddy 注释中所定义...
public init<Collection>(_ collection: Collection) where Collection : Collection, Collection.Element == Freddy.JSON
// Create an instance initialized with `elements`.
public init(arrayLiteral elements: Freddy.JSON...)
鉴于我已经有了数据,这个初始化器是如何使用的?按如下所示的通常方式转换数据就可以了,但我不确定将数据复制为集合的语法。
let json = try JSON(data: data)
如果有帮助,我的目的是获取每个数组的内容并从中创建一个新对象。
[{
"array1": [{
"array1keys": "example",
}],
"array2": [{
"array2keys": "example"
}]
}]
最佳答案
为什么不使用 Swift 提供的开箱即用的 Codable 协议(protocol)?
给定你的 json
let data = """
[
{
"array1": [
{
"array1keys": "example",
}
],
"array2": [
{
"array2keys": "example"
}
]
}
]
""".data(using: .utf8)!
我们可以定义代表您的数据的类型
typealias SubElement = [String:String]
typealias Element = [String:[SubElement]]
typealias Response = [Element]
最后我们可以解码你的 json
if let response = try? JSONDecoder().decode(Response.self, from: data) {
print(response)
}
[["array1": [["array1keys": "example"]], "array2": [["array2keys": "example"]]]]
Usually I would suggest to define a struct conform to
Codable
which makes the code much more easy to read. But in this case this is not possible since there are no fields with a fixed name.
关于json - Freddy JSON - 将集合复制到新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50047365/