Search code examples
iosjsonswiftazure

Parse an object returned as JSON from API in swift


I have recieved a response object (res) in swift from REST API. It is of type. __NSArrayM. It contains a JSON format string which I want to parse.

{ JsonResult = "[ { \"IsAuth\":\"true\" } ]"; }  

It is a long JSON String and I have shortened it for simplicity.

To parse a json, the object needs to be of type Dictionary but I can't cast the object of type __NSArrayM into it.

I searched a lot but can't figure out anyway to read this JSON string.

Additional: Whichever object I try to cast the response object. I get the error -

Could not cast value of type '__NSArrayM' (0x107e86c30) to 'NSData' (0x107e86168)

(or whichever data type I cast into).


Solution

  • Let's do this step by step.

    You say you have an object named "res" which is of type __NSArrayM and which contains this thing:

    { JsonResult = "[ { \"IsAuth\":\"true\" } ]"; } 
    

    It means that you already have converted the JSON to an object, namely an NSArray.

    In this array that we don't see, this thing you're showing us is a dictionary (that we will name "dict") with its value being a String which itself represents another JSON object.

    Let's get the value using the key:

    if let value = dict["JsonResult"] as? String {
        print(value)
    }
    

    Now "value" is supposed to be "[ { \"IsAuth\":\"true\" } ]".

    This is a String which represents JSON. To decode the JSON, we first have to make the string into data then we can decode:

    if let data = value.data(using: .utf8) {
        if let content = try? JSONSerialization.jsonObject(with: data, options: []),
            let array = content as? [[String: Any]]
        {
            print(array)
        }
    }