Chaman sharma
Chaman sharma

Reputation: 41

Dictionary in Swift Not giving Correct Response

I need a response of Dictionary in {} but they give in form[]. Please help. Here is my code

 func getRequestObject() -> Dictionary<String,AnyObject> {
        var requestObject = Dictionary<String,AnyObject>()
        requestObject["username"] = "a"
        requestObject["password"] = "a"
        return requestObject
    }

They give me response like

["password": a, "username": a]

But I need response

{"password": a, "username": a}

Upvotes: 0

Views: 105

Answers (3)

bunty
bunty

Reputation: 629

Check this:

    if let jsonData = try? NSJSONSerialization.dataWithJSONObject(getRequestObject(), options: [])
    {
        let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String

        print(jsonString)
    }

Output

{"password": "a", "username": "a"}

The quotes around "a" is because the type is string. If you don't need quotes, try another quick alternative as below:

    var myString = getRequestObject().description
    let myRange = myString.startIndex..<myString.startIndex.advancedBy(1)
    myString.replaceRange(myRange, with: "{")
    let myRange2 = myString.endIndex.advancedBy(-1)..<myString.endIndex
    myString.replaceRange(myRange2, with: "}")
    print(myString)

Upvotes: 1

Qbyte
Qbyte

Reputation: 13243

Dictionaries in the standard library of Swift have the following syntax:

let dict = [key : value, key : value, ...]

// in your case probably
let dict = getRequestObject()

And printing or converting them to a String results in the same format: [...]

For a format with curly braces you can cast the dictionary to a NSDictionary

let dict2 = dict as NSDictionary

// both result in "{key : value, key : value, ...}"
String(dict2)
print(dict2)

Upvotes: 1

bhumika
bhumika

Reputation: 13

You have to convert your Dictionary to json formate like this way:

do
{
        let jsonData = try NSJSONSerialization.dataWithJSONObject(someDict, options: NSJSONWritingOptions(rawValue:0))

        let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String

        print(jsonString)
    }
    catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }

Upvotes: 1

Related Questions