I want to make one function in my swift project that converts String to Dictionary json format but I got one error:
Cannot convert expression's type (@lvalue NSData,options:IntegerLitralConvertible ...
This is my code:
func convertStringToDictionary (text:String) -> Dictionary<String,String> {
var data :NSData = text.dataUsingEncoding(NSUTF8StringEncoding)!
var json :Dictionary = NSJSONSerialization.JSONObjectWithData(data, options:0, error: nil)
return json
}
I make this function in Objective-C :
- (NSDictionary*)convertStringToDictionary:(NSString*)string {
NSError* error;
//giving error as it takes dic, array,etc only. not custom object.
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
return json;
}
Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all.
Swift 3
Swift 2
Original Swift 1 answer:
In your version, you didn't pass the proper parameters to
NSJSONSerialization
and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:and of course you would also need to change the return type of the function:
Swift 3:
I've updated Eric D's answer for Swift 2:
Swift 4
I found a code which convert the json string to NSDictionary or NSArray.just add the extension SWIFT 3.0
HOW TO USE
EXTENSTION
}
With Swift 3,
JSONSerialization
has a method calledjsonObject(with:options:)
.jsonObject(with:options:)
has the following declaration:When you use
jsonObject(with:options:)
, you have to deal with error handling (try
,try?
ortry!
) and type casting (fromAny
). Therefore, you can solve your problem with one of the following patterns.#1. Using a method that throws and returns a non-optional type
Usage:
#2. Using a method that throws and returns an optional type
Usage:
#3. Using a method that does not throw and returns a non-optional type
Usage:
#4. Using a method that does not throw and returns an optional type
Usage: