0

I'm converting an array of array of dictionaries to string successfully, but converting them back is proving very challenging. Suggestions?

3
  • 1
    no json used but it looks pretty much like JSON Commented Jul 23, 2017 at 21:16
  • The simplest solution is to use JSON. Convert the original array to a JSON string. Then it will be trivial to convert that JSON string back to the original array. Commented Jul 23, 2017 at 21:21
  • Why don't you use 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. Commented Jul 23, 2017 at 21:22

1 Answer 1

6

[[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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, but your code showed only an array of dictionaries. You can obviously adapt it to add in another "array layer"
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
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 !!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.