Swift 3 – How to convert an array of structs that contain structs to JSON?
我有一个要转换为 JSON 字符串的 Field 结构数组。
Field 定义为:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
struct Field{
var name: String func toDictionary() -> [String : Any]{ fileprivate func ppsToDictArray() -> [Any]{ } |
和 LatLng 定义为:
1
2 3 4 5 6 7 8 9 10 11 12 |
struct LatLng{
let latitude: Double func toDictionary() -> [String : Any]{ } |
这是我尝试将数组转换为 JSON 的地方:
1
2 3 4 5 6 7 8 |
//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”\ \ “ } |
如何将此类和数组转换为 JSON 字符串?我尝试了一些类似这个答案的东西,但它打印为 Optional(“[\
\
]”)” (我理解为什么它在打印时显示”可选”)。在推断出我的 structs-within-structs 情况后,我似乎无法让它工作。我也才刚接触 Swift 一个月。
编辑:
我编辑了上面的代码,以代表一个更完整的示例,说明我正在处理的内容,以响应查看更多工作的请求。我最初并没有包括所有这些,因为我不是在问如何修复我现有的代码,而是更多关于如何使用嵌套结构进行处理的示例。
- 让我们看看你的工作。
-
请尝试发布更多代码您正在尝试什么?什么给了你输出Optional(“[\
\
]”)? - developer.apple.com/documentation/foundation/…
- 尽管找到了解决方案,我还是添加了我的工作;我认为这就是它被否决的原因。 @Leo Dabus 这几乎是我需要但找不到的文件。谢谢。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
struct LatLng {
let latitude: Double let longitude: Double func getJSON() -> NSMutableDictionary { struct Field { func getJSON() -> NSMutableDictionary { var perimeterArray = Array<NSMutableDictionary>() values.setValue(name, forKey:”name”) return values } let peri = [LatLng(latitude: 10.0, longitude: 10.0), LatLng(latitude: 20.0, longitude: 20.0)] let field = Field(name:”test”, center: center, perimeter: peri) let json = try NSJSONSerialization.dataWithJSONObject(field.getJSON(), options: .PrettyPrinted) //PRINTS THE FOLLOWING OUTPUT |
更新
为了序列化一个 Field 对象的数组,你可以这样做。
1
2 3 4 5 6 7 8 |
let field1 = Field(name:”value1″, center: center, perimeter: peri)
let field2 = Field(name:”value2″, center: center, perimeter: peri) let field3 = Field(name:”value3″, center: center, perimeter: peri) let fieldArray = [field1.getJSON(), field2.getJSON(), field3.getJSON()] let json = try NSJSONSerialization.dataWithJSONObject(fieldArray, options: .PrettyPrinted) |
请注意,这只是一个快速的解决方案,而不是最好的解决方案。这只是为了让您了解它将如何进行。我相信您将能够改进它。
- 谢谢!非常好和简洁的解决方案。这是我找不到的信息(谷歌搜索”Swift 3 json convert array of struct within struct”并没有删减它,我也不知道相关术语)。
- 您如何建议我序列化整个 Field 对象数组?这是我需要从我的问题中知道的最后一件事。
- 感谢您为我更新!是的,我读了很多关于人们如何使用 Swift 处理 JSON 的资料。它似乎随着时间的推移而迅速变化。我刚从能够使用 Gson 的 Android 来。那个方便的人…
- 在 Swift 4 中要容易得多。因为我目前的项目是在 Swift 2 中,所以我没有在这方面工作太多
来源:https://www.codenong.com/46577534/