Convert a simple string to JSON String in swift
Asked Answered
F

2

10

I know there is a question with same title here. But in that question, he is trying to convert a dictionary into JSON. But I have a simple sting like this: "garden"

And I have to send it as JSON. I have tried SwiftyJSON but still I am unable to convert this into JSON.

Here is my code:

func jsonStringFromString(str:NSString)->NSString{

    let strData = str.dataUsingEncoding(NSUTF8StringEncoding)
    let json = JSON(data: strData!)
    let jsonString = json.string

    return jsonString!
}

My code crashes at the last line:

fatal error: unexpectedly found nil while unwrapping an Optional value

Am I doing something wrong?

Fijian answered 8/4, 2016 at 8:4 Comment(0)
D
27

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"}

Delaine answered 8/4, 2016 at 8:11 Comment(0)
R
4

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)
        }
    }
Robin answered 23/8, 2017 at 21:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.