Arrays Swift Serpent使用顶级数组生成JSON
我正在使用Serpent()使用swift3生成JSON。我的对象模型基本上如下所示:Arrays Swift Serpent使用顶级数组生成JSON,arrays,json,swift,Arrays,Json,Swift,我正在使用Serpent()使用swift3生成JSON。我的对象模型基本上如下所示: import Foundation import Serpent struct FooModel { var features = [FooFeature]() } extension FooModel: Serializable { init(dictionary:NSDictionary?) { features <== (self, dictionary,
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
}
}
但由于我需要阵列是顶级的,所以我应该使用该阵列:
let jsonData = fooModel.features
JSONSerialization.isValidJSONObject(jsonData)
这将导致无效的JSON数据。如何使用Serpent生成所需的JSON格式?Serpent框架为
序列添加了一个扩展,允许您在元素可编码的数组上调用encodableRepresentation()
fooModel.feature.encodableRepresentation()
应该能满足您的需要。WUT!你说得对,谢谢!AppCode中的代码自动完成没有显示任何内容,所以我认为这不起作用,但它毕竟是编译的。
let jsonData = fooModel.features
JSONSerialization.isValidJSONObject(jsonData)