Convert a simple string to JSON String in swift

笑着哭i 提交于 2019-12-03 06:15:56

JSON has to be an array or a dictionary, it can't be only a String.

I suggest you create an array with your String in it:

let array = ["garden"]

Then you create a JSON object from this array:

if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) {
    // here `json` is your JSON data
}

If you need this JSON as a String instead of data you can use this:

if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) {
    // here `json` is your JSON data, an array containing the String
    // if you need a JSON string instead of data, then do this:
    if let content = String(data: json, encoding: NSUTF8StringEncoding) {
        // here `content` is the JSON data decoded as a String
        print(content)
    }
}

Prints:

["garden"]

If you prefer having a dictionary rather than an array, follow the same idea: create the dictionary then convert it.

let dict = ["location": "garden"]

if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []) {
    if let content = String(data: json, encoding: NSUTF8StringEncoding) {
        // here `content` is the JSON dictionary containing the String
        print(content)
    }
}

Prints:

{"location":"garden"}

Swift 3 Version:

    let location = ["location"]
    if let json = try? JSONSerialization.data(withJSONObject: location, options: []) {
        if let content = String(data: json, encoding: .utf8) {
            print(content)
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!