Convert from NSDictionary to [String:Any?]
Hope this helps:
let dict = NSDictionary()
var anyDict = [String: Any?]()
for (value, key) in dict {
anyDict[key as! String] = value
}
convert NSDictionary to NSString
You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:
[NSString stringWithFormat:@"my dictionary is %@", aDictionary];
or
NSLog(@"My dictionary is %@", aDictionary);
How to convert NSDictionary to NSString which contains json of NSDictionary in Swift?
You can use the following code:
var error: NSError?
var dict: NSDictionary = [
"1": 1,
"2": "Two",
"3": false
]
let data = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted, error: &error)
if let data = data {
let json = NSString(data: data, encoding: NSUTF8StringEncoding)
if let json = json {
println(json)
}
}
Given a NSDictionary
, it is serialized as NSData
, then converted to NSString
.
The code doing the conversion can also be rewritten more concisely as:
Swift 3:
do {
let jsonData = try JSONSerialization.data(withJSONObject: data)
if let json = String(data: data, encoding: .utf8) {
print(json)
}
} catch {
print("something went wrong with parsing json")
}
Original answer:
if let data = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
if let json = NSString(data: data, encoding: NSUTF8StringEncoding) {
println(json)
}
}
Note that in order for the serialization to work the dictionary must contain valid JSON keys and values.
How do I convert NSDictionary to Dictionary?
NSDictionary
in Objective-C has always non-optional values.AnyObject
has becomeAny
in Swift 3.- Considering the first two "rules"
NSDictionary
can be bridge cast toDictionary
let post_paramsValue = post_params as Dictionary<String,Any>
If the source NSDictionary
is an optional you might use as Dictionary<String,Any>?
or as? Dictionary<String,Any>
or as! Dictionary<String,Any>
or as Dictionary<String,Any>!
depending on the actual type of the NSDictionary
How do I convert swift Dictionary to NSDictionary
You have to cast it like this:
let dict = parcelDict as NSDictionary
Otherwise the Swift Dictionary and NSDictionary are treated almost the same way when using it in methods for ex:
func test(dict: NSDictionary) {}
let dict = ["Test":1]
test(dict)
Will work completely fine.
After your update
If you change your Dictionary value type to non optional String then your error will go away.
[String:String?] change to -> [String:String]
Swift NSDictionary JSON Array to String Convert Time consuming
You don't need to convert your JSON data to String, and you certainly shouldn't ever process the JSON string itself anyway.
To save your dictionary as JSON, just convert the dictionary to JSON data then save the data:
let jsonData = try NSJSONSerialization.dataWithJSONObject(yourDictionary, options: [])
// save `jsonData` in your SQL
Here jsonData
is your JSON data. This is what you need to save. Nothing else.
You can save this in an SQL table by saving it as blob
(a chunk of data) instead of String.
Then to get it back:
let jsonData = // get the blob from SQL
if let json = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: []),
let dict = json as? [String: AnyObject]
{
// here `dict` is your dictionary converted from JSON data
}
See? No need for converting the JSON data to or from String.
Last suggestion: don't use NSDictionary and NSArray. Instead, use Swift arrays and Swift dictionaries. It's easier and safer.
Cannot subscript a value of type NSDictionary with an index of type String. While converting from Swift 2.3 - 3.2
Use native types
if let dataToProcess = dict["data"] as? [String:Any],
let productDataRecord = dataToProcess["productDataRecord"] as? [String:Any],
let module = productDataRecord["module"] as? [[String:Any]] {
for value in module {
if let cpmChild = value["cem:canadaExtensionModule"] as? [String:Any],
let tempDict = cpmChild["retailPackSize"] as? [String:Any],
let myValue = tempDict["value"] as? String {
productToReturn.planoRetailPackSize = myValue
}
}
}
Note : In the for
loop myValue
will overwrite planoRetailPackSize
in each iteration. This is most likely not intended.
Related Topics
How to Know If a Swiftui Button Is Enabled/Disabled
How to Use The Delegates with Nskeyedunarchiver
How to Initialize UIbezierpath to Draw a Circle in Swift
How to Handle Error with Realm During Writing
Decrypted String Always Returning Null
Pfobject Unable to Be Cast to Custom Subclass
Module Compiled with Swift X.1 Cannot Be Imported in Swift X.0.2
How to Calculate Quadrangle for Visible Part of Vertical Plane
Nsmanagedobjectcontext's Propagatesdeletesatendofevent Set to False Causes Error on Save
Type 'Int' Does Not Conform to Protocol 'Booleantype'
Is There Any Reasonable Way to Access The Contents of a Characterset
Using UIdropinteractiondelegate and Movies
How to Initialize a Struct with a Closure Parameter Like This
How to Use Axobserveraddnotification in Swift
iOS 10 App Crashes When Accessing Camera