简体   繁体   中英

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}

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

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)

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)

So you want the description of a dictionary to use {} instead of [] ? That's easy, just some string manipulation would do the job!

We need to set the first and last char of the string to "{" and "}". So let's write a setChar function:

func setChar (at index: Int, _ str: String, to ch: Character) -> String {
    var charArr = Array(str.characters)
    charArr[index] = ch
    var finalString = ""
    for c in charArr {
        finalString += String(c)
    }
    return finalString
}

I just split the chars into an array, set the char, then join them all together again and return.

Now you can first get the description of the dictionary:

var description = getRequestObject().description

And then call the function:

description = setChar(at: 0, description, to: "{")
description = setChar(at: description.characters.count - 1, description, to: "}")

And BOOM! You will see the expected result!

You can even make the setChar function an extension of String !

extension String {
    func setChar (at index: Int, to ch: Character) -> String {
        var charArr = Array(self.characters)
        charArr[index] = ch
        var finalString = ""
        for c in charArr {
            finalString += String(c)
        }
        return finalString
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM