我使用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格式?
答案 0 :(得分:2)
Serpent
框架为Sequence
添加了一个扩展程序,允许您在元素为encodableRepresentation()
的数组上调用Encodable
。
fooModel.feature.encodableRepresentation()
应该能满足您的需求。