私は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]")"
として印刷されます(印刷時に「オプション」と表示される理由を理解しています)。私はstructs-within-structsの状況のために外挿した後に動作するようには思えません。私はスウィフトにも約1ヶ月しかいません。
EDIT: 私は上記のコードを編集して、より多くの作業を見たいという要求に応えて、私が取り組んでいた作業のより完全な例を示しました。元のコードを修正する方法を尋ねるのではなく、ネストされた構造体を使用してプロセスを実行する方法の例については、もともとはすべてを含めなかった。
あなたの作品を見てみましょう。 –
あなたは何をしようとしているより多くのコードを投稿しようとしていますか?そして、あなたに出力 'Optional(" [\ n \ n] ")'を与えるものは何ですか? –
https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types –