arrays - Swift Serpent 使用顶级数组生成 JSON

标签 arrays json swift

我正在使用 Serpent ( https://github.com/nodes-ios/Serpent ) 通过 Swift 3 生成 JSON。我的对象模型基本上如下所示:

import Foundation
import Serpent

struct FooModel
{
    var features = [FooFeature]()
}
extension FooModel: Serializable
{
    init(dictionary:NSDictionary?)
    {
        features <== (self, dictionary, "features")
    }

    func encodableRepresentation() -> NSCoding
    {
        let dict = NSMutableDictionary()
        (dict, "features") <== features
        return dict
    }
}

struct FooFeature
{
    var uri = ""
    var id = ""
    var keyword = ""
    var name = ""
    var tags = [FooTag]()
}
extension FooFeature: Serializable
{
    init(dictionary:NSDictionary?)
    {
        uri <== (self, dictionary, "uri")
        id <== (self, dictionary, "id")
        keyword <== (self, dictionary, "keyword")
        name <== (self, dictionary, "name")
        tags <== (self, dictionary, "tags")
    }

    func encodableRepresentation() -> NSCoding
    {
        let dict = NSMutableDictionary()
        (dict, "uri") <== uri
        (dict, "id") <== id
        (dict, "keyword") <== keyword
        (dict, "name") <== name
        (dict, "tags") <== tags
        return dict
    }
}

struct FooTag
{
    var name = ""
    var line = 0
}
extension FooTag: Serializable
{
    init(dictionary:NSDictionary?)
    {
        name <== (self, dictionary, "name")
        line <== (self, dictionary, "line")
    }

    func encodableRepresentation() -> NSCoding
    {
        let dict = NSMutableDictionary()
        (dict, "name") <== name
        (dict, "line") <== line
        return dict
    }
}

...等等。但是,我为其编写 JSON 输出的工具需要一个数组作为顶级。在这种情况下,它将是 features 数组。

我通常会这样做来获取 JSON 字典:

let jsonData = fooModel.encodableRepresentation()

但是因为我需要数组是顶级的,所以我应该使用那个数组:

let jsonData = fooModel.features
JSONSerialization.isValidJSONObject(jsonData)

这会导致无效的 JSON 数据。如何使用 Serpent 生成所需的 JSON 格式?

最佳答案

Serpent 框架为 Sequence 添加了一个扩展,允许您在元素为 Encodable 的数组上调用 encodableRepresentation()

fooModel.feature.encodableRepresentation() 应该可以满足您的需求。

关于arrays - Swift Serpent 使用顶级数组生成 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45832003/

相关文章:

arrays - Postgresql - 检查给定字符串是否以字符串数组的任何元素开头

java - GSON 序列化 - 如何从序列化中排除某些字段,但不从反序列化中排除

ios - 禁用 segue 动画

swift - swift 3 中的增量错误

swift - Swift 是否有任何内置的 Bool 反向函数?

java - 关于数组不返回预期值的简单代码片段

c - 在 C 中分配给数组

java - Retrofit JSON 解析中出现错误的 IllegalStateException

python - 从 JSON 生成数据帧

python - 查找两个数组的非交叉值