I have an array of Field
structs that I want to convert to a JSON string.
Field
is defined as:
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
}
}
and LatLng
is defined as:
struct LatLng{
let latitude: Double
let longitude: Double
func toDictionary() -> [String : Any]{
let dict: [String : Any] = ["latitude": self.latitude,
"longitude": self.longitude]
return dict
}
}
Here's where I'm trying to convert my array to 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"
}
How can I convert such and array to a JSON string? I attempted something along the lines of this answer, but it prints as Optional("[\n\n]")"
(I understand why it says "Optional" when printing). I can't seem to get it to work after extrapolating for my structs-within-structs situation. I'm also only about a month into Swift.
EDIT: I edited the above code to represent a more complete example of what I was working on in response to a request to see more work. I didn't include all of that originally because I wasn't asking how to fix my existing code, but more for an example of how to go about the process with nested structs.