Swift Serpent使用顶级数组生成JSON

时间:2017-08-23 06:19:03

标签: 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格式?

1 个答案:

答案 0 :(得分:2)

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

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