我正在使用 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/