Parse the value from string value iOS swift

Problem:

How to parse the string that contains the json value? 

Solution:

extension String {

    var parseJSONString: AnyObject?

    {

        let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)

        if let jsonData = data

        {

            // Will return an object or nil if JSON decoding fails

            do

            {

                let message = try JSONSerialization.jsonObject(with: jsonData, options:.mutableContainers)

                if let jsonResult = message as? NSMutableDictionary

                {

                    return jsonResult //Will return the json array output

                }

                else if let jsonResult = message as? NSMutableArray

                {

                    return jsonResult //Will return the json array output

                }

                else {

                    return nil

                }

            }

            catch let error as NSError

            {

                print("An error occurred: \(error)")

                return nil

            }

        }

        else

        {

            // Lossless conversion of the string was not possible

            return nil

        }

    }

}

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

store cgpoint in userdefaults iOS swift