Search code examples
jsonswiftnsdictionary

How to serialize JSON string to multidimensional NSDictionary


"[{\"person\":\"person1\",\"data\":{\"age\":\"10\",\"name\":\"John\"}},
{\"person\":\"person2\",\"data\":{\"age\":\"20\",\"name\":\"Jonathan\"}},
{\"person\":\"person3\",\"data\":{\"age\":\"30\",\"name\":\"Joe\"}}]"

Note that the value "data" is also a dictionary.

I have a JSON string like above and am trying to serialize like:

if let dataFromString = conf.data(using: .utf8, allowLossyConversion: false) {
        let json = try JSON(data: dataFromString)
        
        configuration = json.dictionary ?? [:]
    }

However configuration is always an empty dictionary.


Solution

  • You need to parse the JSON you've as an array of dictionaries of type [[String: Any]]. The better modern approach is to use Decodable model to decode the JSON.

    let string = """
    [
        {
            "person": "person1",
            "data": {
                "age": "10",
                "name": "John"
            }
        },
        {
            "person": "person2",
            "data": {
                "age": "20",
                "name": "Jonathan"
            }
        },
        {
            "person": "person3",
            "data": {
                "age": "30",
                "name": "Joe"
            }
        }
    ]
    """
    
    let data = Data(string.utf8)
    
    struct Person: Decodable {
        let person: String
        let data: PersonData
    }
    
    struct PersonData: Decodable {
        let age, name: String
    }
    
    do {
        let people = try JSONDecoder().decode([Person].self, from: data)
        print(people)
    } catch { print(error) }