有什么方法可以使用JSONEncoder

时间:2019-04-04 11:47:42

标签: ios swift

在这里词典

struct Person : Codable {
    let name : String?
    let city : String?
    let age : Int?
}

let dic : [String : Any] = 
    ["name":"Manna","city" : "Rangpur", "age": 18,
     "name":"Munna","city" :"Dhaka","age":19,
     "name":"Shaon","city" :"Rangpur","age":11,
     "name":"Limon","city" :"Tangail","age":15,
     "name":"Lalon","city" :"Rangpur","age":18,
     "name":"Rakib","city" :"Dhaka","age":15, 
     "name":"Mum","city" :"Rangpur","age":18,
     "name":"Man","city" :"Bogura","age":12,
     "name":"Limon","city" :"Tangail","age":18]


// let manna = Person(name: "Manna", city: "Rangpur", age: 18)
// Here i want to use the dictionary

    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted

    do {
         let data  = try encoder.encode(manna)
         print(String(data: data, encoding: .utf8)!)
    } catch {
        print("error : \(error.localizedDescription)")
    }

尝试使用JSONEncoder将这个字典像json文件一样编码为输出

1 个答案:

答案 0 :(得分:0)

首先,您的字典有误,因为字典不包含相同的键。

您可以像字典数组一样呈现它

let dic : [[String : Any]] = [["name":"Manna", "city" : "Rangpur", "age": 18],
                            ["name":"Munna","city" :"Dhaka","age":19,],
                            ["name":"Shaon","city" :"Rangpur","age":11,],
                            ["name":"Limon","city" :"Tangail","age":15,],
                            ["name":"Lalon","city" :"Rangpur","age":18,],
                            ["name":"Rakib","city" :"Dhaka","age":15,],
                            ["name":"Mum","city" :"Rangpur","age":18,],
                            ["name":"Man","city" :"Bogura","age":12,],
                            ["name":"Limon","city" :"Tangail","age":18]]

现在您可以将字典数组转换为JSON,如下所示

if let data = try? JSONSerialization.data(withJSONObject: dic, options: JSONSerialization.WritingOptions.prettyPrinted) {
    print(data.count)
    let json = String(data: data, encoding: String.Encoding.utf8)
    print(json ?? "")
}