I'm converting an array of array of dictionaries to string successfully, but converting them back is proving very challenging. Suggestions?
1 Answer
[[String: Any]] is not an "array of array of dictionaries". It's an array of dictionaries. Here's an example with JSON:
func toJSON(array: [[String: Any]]) throws -> String {
let data = try JSONSerialization.data(withJSONObject: array, options: [])
return String(data: data, encoding: .utf8)!
}
func fromJSON(string: String) throws -> [[String: Any]] {
let data = string.data(using: .utf8)!
guard let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [AnyObject] else {
throw NSError(domain: NSCocoaErrorDomain, code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid JSON"])
}
return jsonObject.map { $0 as! [String: Any] }
}
Test:
let array: [[String: Any]] = [
[
"firstName": "John",
"lastName": "Smith"
],
[
"make": "Ford",
"model": "Focus",
"year": 2016
]
]
let str = try! toJSON(array: array)
let array2 = try! fromJSON(string: str)
print(array2)
The key to JSON is that you must decode one level at a time.
3 Comments
Code Different
Yes, but your code showed only an array of dictionaries. You can obviously adapt it to add in another "array layer"
Code Different
Can you add an example input and desired output? It's hard to track what you want with comments. Also, your manual JSON encoding doesn't produce valid JSON
Sean Rice
My string was not malformed, but the data within was. As stated in Apple Developer docs on subject of custom metadata storage on HKWorkout ... only NSString, NSNumber, or NSDate objects are supported as values. Period. The conversion routine was correct but I was trying to store a Tuple, several Booleans and several custom structs. Thanks CD !!!
JSONSerialization? It's straightforward and easy to use. (and there are millions of examples here on SO). By the way: your code is not valid JSON because a dictionary is represented by{}and the last element of a collection is not terminated by a comma.