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

前端 未结 1 1311
一生所求
一生所求 2021-01-27 15:46

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

Field is defined as:

struct Field{

    var name: St         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-27 16:45

    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()
            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.

    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.

    0 讨论(0)
提交回复
热议问题