Swift 3-如何将包含结构的结构数组转换为JSON? [英] Swift 3 - How to convert an array of structs that contain structs to JSON?

查看:247
本文介绍了Swift 3-如何将包含结构的结构数组转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要转换为JSON字符串的Field结构数组.

I have an array of Field structs that I want to convert to a JSON string.

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:

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"
    }

如何将此类和数组转换为JSON字符串?我尝试按照此答案的方法进行操作,但是它显示为Optional("[\n\n]")"(我理解为什么它说可选"打印时).在针对我的结构中"情况进行推断后,我似乎无法使其工作.我也只有大约一个月的时间进入Swift.

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.

我对上面的代码进行了编辑,以表示我正在为响应查看更多工作的请求而进行的工作的更完整示例.我之所以没有包含所有这些内容,是因为我不是在问如何修复现有代码,而是想知道如何使用嵌套结构进行处理的示例.

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
    }]
})

更新

为了序列化Field对象的数组,您可以执行以下操作.

In order to serialise an array of Field objects, you can do something like this.

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.

这篇关于Swift 3-如何将包含结构的结构数组转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆