Convert String to NSDictionary by ignoring string literal - swift

I'm getting dictionary value from server in form of String. Now when I try to use that String, it contains \ before ".
I get below value from my web service:
“\”{\\\”111\\\”:\\\”abc\\\”, \\\”222\\\”:\\\”xyz\\\”}\”
I'm trying to convert this string to NSDictionary. Can you please some one guide me for this. Which is the easiest way to convert this to NSDictionary. My current code is as below, but it's not working
var permValue = perm.value?.stringByReplacingOccurrencesOfString("\\", withString: "")
let data = permValue?.dataUsingEncoding(NSUTF8StringEncoding)
if let dict = try! NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary{
print("Permission Dictionary : \(dict)")
}
I'm getting an error while converting data to NSDictionary.
Please help. Any help will be appreciated

Related

Convert string to dictionary?

I have a QR code scanner which reads QR codes as a string. There are no options to detect it as a dictionary. So the only solution would be to convert it to a dictionary (i think). Keep in mind I am using swift and using AVFoundation, which is from apple.
This QR code would print out ["test": "test123"] as a string. How would I convert it to a dictionary?
Here's what I've came up with. Output is not dictionary though.
let test = "[\"test\": \"test123\"]"
let data = test.data(using: .utf8)!
do{
let output = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:String]
print ("\(String(describing: output))")
}
catch {
print (error)
}

error when convert JSON to Dictionary Swift

can you help me,
I'm facing an issue if the JSON came with multilines like this
"{\"groupId\":\"58\",\"chat\":\"send 2lines\nsecondline\"}"
I'm taking the response from server and convert it with this function
let dataDic = self.convertToDictionary(text: (remoteMessage.appData["message"]! as AnyObject) as! String)
print(dataDic!)
and this is my function
func convertToDictionary(text: String) -> [String: AnyObject]? {
if let data = text.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
return json
} catch {
print(error.localizedDescription)
}
}
return nil
}
but the problem came if the code have multilines because it's put \n in the return and
it gives me
The data couldn’t be read because it isn’t in the correct format
Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control character around character 145." UserInfo={NSDebugDescription=Unescaped control character around character 145.}
You should put an extra "\" before "\n", before parsing your JSON. Try using "replacingOccurencesOf" function.
That way your JSON is formatted before parsing.

Read data from Firebase to swift3 EXC_BAD_INSTRUCTION

I have the following firebase database
This is how I add data into the database
And this is how I try to get the data out of Database but I get this error EXC_BAD_INSTRUCTION
Your force unwrap is saying that the dictionary should only consist of String: String. But as you can see, the value for the key value is an integer, which will be parsed as an NSNumber according to the Firebase documentation so String: AnyObject is what you want to unwrap as.
let snapshotValue = snapshot.value as Dictionary<String, AnyObject>
A little bit of safer code would be:
guard let snapshotValue = snapshot.value as? Dictionary<String, AnyObject>
else {
return
}
The error appears because my database value is Integer and I want to read it as String.

Syntax about try and "as?" "as!"

I read a snippet from this POST but have not quite understood.
https://www.hackingwithswift.com/example-code/system/how-to-parse-json-using-nsjsonserialization
I am confused on some syntax in the following snippets.
In the following, I am not knowing why try goes here, it is strange syntax to me. Any information about try and as! for this expression?
let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: AnyObject]
In the following, I am not knowing what is as? [String] doing?
if let names = json["names"] as? [String] {
I know this question might be fundamental, I just need a keyword for me to search the related anwser, thanks. Here is my whole code block.
// define a string
let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
// convert the string into NSUTF8StringEncoding
let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
// put the following statements in try catch block
do {
// not knowing why try goes here, strange syntax to me.
// any higher conception about try and as! for this expression
let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: AnyObject]
// json should be an object(dictionary, hash) use the key "names" to store string array into names
// not knowing what is `as? [String]` doing? any keyword for this syntax?
if let names = json["names"] as? [String] {
print(names)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
// not knowing why try goes here, strange syntax to me. what if it fails? as! is what syntax, any keyword to search for it?
The try here is to basically to try to perform the function on that line. If it fails it will go to the catch. Which in this case will just print("Failed to load: \(error.localizedDescription)")
// json should be an object(dictionary, hash) use the key "names" to store string array into names // not knowing what is as? [String] doing? any keyword for this syntax?
The line that you are confuse about is performing a if else on the json object. It check for a key that is name and also want to ensure that its value is a String therefore the as?. In this case if the key name does not exist it will not met the condition. If the value of name is not a String it will not met the condition.
Like what #Martin R mention in the comments, you should read up more on Type Casting in Swift. This should help you. Explanation with some example if you have trouble with Apple Documentation.
As for try catch it is actually use in other languages as well not just Swift. You can read up more here.

Swift: How to convert string to dictionary

I have a dictionary which i convert to a string to store it in a database.
var Dictionary =
[
"Example 1" : "1",
"Example 2" : "2",
"Example 3" : "3"
]
And i use the
Dictionary.description
to get the string.
I can store this in a database perfectly but when i read it back, obviously its a string.
"[Example 2: 2, Example 3: 3, Example 1: 1]"
I want to convert it back to i can assess it like
Dictionary["Example 2"]
How do i go about doing that?
Thanks
What the description text is isn't guaranteed to be stable across SDK versions so I wouldn't rely on it.
Your best bet is to use JSON as the intermediate format with NSJSONSerialization. Convert from dictionary to JSON string and back.
I created a static function in a string helper class which you can then call.
static func convertStringToDictionary(json: String) -> [String: AnyObject]? {
if let data = json.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String: AnyObject]
if let error = error {
println(error)
}
return json
}
return nil
}
Then you can call it like this
if let dict = StringHelper.convertStringToDictionary(string) {
//do something with dict
}
this is exactly what I am doing right now. Considering #gregheo saying "description.text is not guaranteed to be stable across SKD version" description.text could change in format-writing so its not very wise to rely on.
I believe this is the standard of doing it
let data = your dictionary
let thisJSON = try NSJSONSerialization.dataWithJSONObject(data, options: .PrettyPrinted)
let datastring:String = String(data: thisJSON, encoding: NSUTF8StringEncoding)!
you can save the datastring to coredata.