How to assign elements of a dictionary to JSON object in Vapor 3?

戏子无情 提交于 2019-12-06 09:13:27
Alan

This is basically, JSON serialization in swift. Decoding the JSON object to a Dictionary and then modifying the dictionary and creating a new JSON.

router.get("test") { req -> String in

    let jsonDic = ["name":"Alan"]
    let data = try JSONSerialization.data(withJSONObject: jsonDic, options: .prettyPrinted)
    let jsonString = String(data: data, encoding: .utf8)
    return jsonString ?? "FAILED"
}

router.get("test2") { req -> String in
    do {
        // Loading existing JSON
        guard let url = URL(string: "http://localhost:8080/test") else {
            return "Invalid URL"
        }

        let jsonData = try Data(contentsOf: url)
        guard var jsonDic = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [String:String] else {
            return "JSONSerialization Failed"
        }

        // Apply Changes
        jsonDic["name"] = "John"

        // Creating new JSON object
        let data = try JSONSerialization.data(withJSONObject: jsonDic, options: .prettyPrinted)
        let jsonString = String(data: data, encoding: .utf8)
        return jsonString ?? "FAILED"
    }catch{
        return "ERROR"
    }
}

I strongly recommend to create struct or class for your data type. It would be much safer in casting using the codable protocol and much easier to convert between JSON and your objects type because of the content protocol in vapor version 3.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!