简体   繁体   English

Swift 3 - 如何将包含结构的结构数组转换为 JSON?

[英]Swift 3 - How to convert an array of structs that contain structs to JSON?

I have an array of Field structs that I want to convert to a JSON string.我有一个要转换为 JSON 字符串的Field结构数组。

Field is defined as: 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
    }


}

and LatLng is defined as: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
    }

}

Here's where I'm trying to convert my array to JSON:这是我尝试将数组转换为 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?如何将此类和数组转换为 JSON 字符串? 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.我按照这个答案的思路尝试了一些东西,但它打印为Optional("[\\n\\n]")" (我理解为什么它在打印时说“可选”)。我似乎无法让它工作推断我的结构内结构情况。我也只有大约一个月的 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.我最初没有包括所有这些,因为我不是在问如何修复我现有的代码,而是更多关于如何使用嵌套结构进行过程的示例。

struct LatLng {
    let latitude: Double
    let longitude: Double

    func getJSON() -> NSMutableDictionary {
        let dict = NSMutableDictionary()
        dict.setValue(latitude, forKey: "latitude")
        dict.setValue(longitude, forKey: "longitude")
        return dict
    }
}

struct Field {
    var name: String
    var center: LatLng
    var perimeter: [LatLng]

    func getJSON() -> NSMutableDictionary {
        let values = NSMutableDictionary()

        var perimeterArray = Array<NSMutableDictionary>()
        for item in perimeter {
            perimeterArray.append(item.getJSON())
        }

        values.setValue(name, forKey: "name")
        values.setValue(center.getJSON(), forKey: "center")
        values.setValue(perimeterArray, forKey: "perimeter")

        return values

    }
}

let peri = [LatLng(latitude: 10.0, longitude: 10.0), LatLng(latitude: 20.0, longitude: 20.0)]
let center = LatLng(latitude: 15.0, longitude: 15.0)

let field = Field(name: "test", center: center, perimeter: peri)

let json = try NSJSONSerialization.dataWithJSONObject(field.getJSON(), options: .PrettyPrinted)
let jsonString = NSString(data: json, encoding: NSUTF8StringEncoding)
print(jsonString)

//PRINTS THE FOLLOWING OUTPUT
Optional({
    "name" : "test",
    "center" : {
        "longitude" : 15,
        "latitude" : 15
    },
    "perimeter" : [{
        "longitude" : 10,
        "latitude" : 10
    },
    {
        "longitude" : 20,
        "latitude" : 20
    }]
})

UPDATE更新

In order to serialise an array of Field objects, you can do something like this.为了序列化 Field 对象的数组,您可以执行以下操作。

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)
let jsonString = NSString(data: json, encoding: NSUTF8StringEncoding)

Please note that this is just a quick solution, not the best one.请注意,这只是一种快速解决方案,而不是最好的解决方案。 This is just to give you an idea of how it will go.这只是为了让您了解它将如何进行。 I'm sure you'll be able to improve on it.我相信你可以改进它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM