【问题标题】:Swift3 Array convert in String like "{\"type\": \"0\"}"Swift3 数组转换为字符串,如 "{\"type\": \"0\"}"
【发布时间】:2017-08-18 06:46:27
【问题描述】:

我在 Swift 中创建了一个数组。我有一个 node.js API,在这个 API 中只传递这样的字符串类型数据

 let Dic = "{\"type\": \"0\",\"message\": \"\(message)\", \"sender_id\":\"\(username)\", \"reciever_id\": \"61\", \"\(username)\": \"2017-05-09 03:02:55 PM\"}"

我无法在 API 中传递这个 Dic。但问题是,我有一个数组,如何将数组转换为字符串。我必须在 Dic 中再添加一个参数,然后传递这个数组 这是我的代码如何生成这个数组

(
        {
        Desc = "This is suger for m23 type ";
        Price = 50;
        Product = "Suger temp";
    },
        {
        Desc = "This is suger for m23 type ";
        Price = 50;
        Product = "Suger temp";
    }
)

代码是

let ary_allPRoduct :NSMutableArray = []

            for i in 0..<count {
                var dict = Dictionary<String, Any>()
                dict["Product"]="Suger temp"
                dict["Desc"]="This is suger for m23 type "
                dict["Price"]="50"

                ary_allPRoduct.add(dict)

            }

            print(ary_allPRoduct)

【问题讨论】:

    标签: arrays string swift3 parameter-passing


    【解决方案1】:

    在 Swift 中,请应用此代码。

    let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: JSONSerialization.WritingOptions())
    let jsonString = NSString(data: jsonData!, encoding: String.Encoding.utf8.rawValue)
    print(jsonString)
    

    注意:在控制台上它通常会打印字符串。但是如果你在断点上检查它。你会看到你需要的确切格式,它应该可以工作。

    在控制台上:({"nacho":["1","2","3"]})

    并且 How its should look on Breakpoint

    【讨论】:

    • jsonString 可以创建更短的let jsonString = String(data: jsonData!, encoding: .utf8)。在 Swift 中根本不需要使用NSString,您可以在data(withJSONObject 中省略options 参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 2017-06-05
    • 2021-12-13
    • 1970-01-01
    • 2017-11-27
    • 2015-11-11
    相关资源
    最近更新 更多