Get Specific key value from JSON inside another JSON value in Siwft

132 Views Asked by At

I have a JSON where it contains a key value as another JSON. How to get the second JSON key value?

{
currentEnvironment = prod;
prodappRatingCount = 2;
proddefaultCourse = "<null>";
“Check” = { "user":null,"removeDownloadedContents":true,"successCallBack":""}";
prodfirstTime = no;}

I want the value removeDownloadedContents key. How to get it using Swift

1

There are 1 best solutions below

0
Coskun Caner On

At the first you must use a proper JSON syntax, otherwise you can never ever parse it, here is an example for woking JSON:

...

{
    "currentEnvironment" : "prod",
    "prodappRatingCount" : 2,
    "proddefaultCourse" : "<null>",
    "Check" : 
    { 
        "user":null,
        "removeDownloadedContents":true,
        "successCallBack":""
    },
    "prodfirstTime" : false
}

... and here is a sample swift code to parse it: ...

// MARK: - SampleContainer
struct ContainerObject: Codable {
    var currentEnvironment: String?
    var prodappRatingCount: Int?
    var proddefaultCourse: String?
    var check: CheckObject?
    var prodfirstTime: Bool?

    enum CodingKeys: String, CodingKey {
        case currentEnvironment = "currentEnvironment"
        case prodappRatingCount = "prodappRatingCount"
        case proddefaultCourse = "proddefaultCourse"
        case check = "Check"
        case prodfirstTime = "prodfirstTime"
    }
}

// MARK: - Check
struct CheckObject: Codable {
    var user: UserObject?
    var removeDownloadedContents: Bool?
    var successCallBack: String?

    enum CodingKeys: String, CodingKey {
        case user = "user"
        case removeDownloadedContents = "removeDownloadedContents"
        case successCallBack = "successCallBack"
    }
}

// MARK: - User
struct UserObject:Codable {
    // id, name, ...
}


// MARK: - URLSession response handlers

extension URLSession {
    fileprivate func codableTask<T: Codable>(with url: URL, completionHandler: @escaping (T?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
        return self.dataTask(with: url) { data, response, error in
            guard let data = data, error == nil else {
                completionHandler(nil, response, error)
                return
            }
            completionHandler(try? JSONDecoder().decode(T.self, from: data), response, nil)
        }
    }

    func getContainerTask(with url: URL, completionHandler: @escaping (ContainerObject?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
        return self.codableTask(with: url, completionHandler: completionHandler)
    }
}

... and this is how you can call the parser in your controller to fetch your data objects: ...

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        // To read values from URLs:
        let url = URL(string: "https://your.super.cool.api.site.com/endpoint")!
        let task = URLSession.shared.getContainerTask(with: url) { sampleContainer, response, error in
            if let sampleContainer = sampleContainer {
                //... use your objects here..
                if let shouldRemove = sampleContainer.check?.removeDownloadedContents {
                    //...
                }
            }
        }
        task.resume()
    }

}

...

Related Questions in IOS

Related Questions in JSON

Related Questions in SWIFT