我有一个数组Field
我想要转换为JSON字符串的结构。Swift 3 - 如何将包含结构的结构数组转换为JSON?
Field
被定义为:
struct Field{
var name: String
var center: LatLng
var perimeter: [LatLng]
func toDictionary() -> [String : Any]{
let dict: [String : Any] = ["name":self.name,
"center":self.center.toDictionary(),
"perimeter": ppsToDictArray()]
return dict
}
fileprivate func ppsToDictArray() -> [Any]{
var data = [Any]()
for pp in perimeterPoints{
data.append(pp.toDictionary())
}
return data
}
}
和LatLng
被定义为:
struct LatLng{
let latitude: Double
let longitude: Double
func toDictionary() -> [String : Any]{
let dict: [String : Any] = ["latitude": self.latitude,
"longitude": self.longitude]
return dict
}
}
这里的我想在哪里我的数组转换成JSON:
//selectedFields is a [Field] populated with some Fields
let dicArray = selectedFields.map{$0.toDictionary()}
if let data = try? JSONSerialization.data(withJSONObject: dicArray, options: .prettyPrinted){
let str = String(bytes: data, encoding: .utf8)
print(str) //Prints a string of "\n\n"
}
如何我可以将这样的数组转换为JSON字符串吗?我尝试了一些沿着this answer的行,但打印为Optional("[\n\n]")"
(我明白为什么打印时显示“可选”)。在推断我的结构内部结构情况后,我似乎无法完成它的工作。我也只有大约一个月进入Swift。
编辑: 我编辑了上面的代码,以表示一个更完整的例子,说明了我正在处理的一个响应请求以查看更多工作的内容。我原来并没有包含所有这些,因为我并没有问如何解决现有的代码,而更多的是关于如何使用嵌套的结构来处理这个过程的例子。
让我们来看看你的工作。 –
请试着张贴更多的代码你正在尝试?什么给你输出'Optional(“[\ n \ n]”)'? –
https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types –