json - Freddy JSON - 将集合复制到新数组中

标签 json swift deserialization

在 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/

相关文章:

JSON JQ 如果没有 else

javascript - JSON 数据未出现在 iOS 中的响应 header 中

ios - GCDAsyncSocket 不向 TCP 套接字服务器发送数据

ios - 当我的游戏结束时,我需要 'send' 将分数保存到 TableView Controller 的变量

ios - 创建构建文件时 Xcode 9.4 崩溃

java - 从自定义反序列化器访问@JackonInject值

JSON 解码为 struct 作为 interface{} 产生 map[string]interface{},而不是 struct

mysql - JSON 数据更新不起作用(MySQL)

android - Gson 解析数据有时是字符串,有时是对象

c# - 如果我不知道正确的类型,如何反序列化一个对象?