我有一個數組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 –