Shrestha Goyal
Shrestha Goyal

Reputation: 51

How do I parse a nested JSON.I am getting nil value as an output

These are the structs I have created

struct main : Decodable{      // these are the values I want to retrieve 
        let catname : String?
        let catid : String?
        let sub_title : String?
        let image : String?
        let contest : [contest]

    enum CodingKeys : String , CodingKey {
        case catname = "catname"
        case catid = "catid"
        case sub_title = "sub_title"
        case image = "image"
        case contest = "contest"
    }

}
struct  contest : Decodable {
    let id : Int
    let name : String
    let entryfee : Int
    let contest_type : String
    let winning_percentage : Int
    let win_amount : Int
    let matchkey : String
    let c_type : String
    let status : Int
    let joinedusers : Int
    let maximum_user : Int
    let getjoinedpercentage : String
    let multi_entry : Int
    let confirmed_challenge : Int
    let is_running : Int
    let is_bonus : Int
    let bonus_percentage : Int
    let isselected : Bool
    let isselectedid : String
    let refercode : String
    var price_card : [price_card]
    let totalwinners : Int
    enum CodingKeys : String, CodingKey{
        case id , name , entryfee , contest_type , winning_percentage ,win_amount,matchkey,c_type,status,joinedusers,maximum_user,getjoinedpercentage,multi_entry,confirmed_challenge,is_running,is_bonus,bonus_percentage,isselected,isselectedid,refercode,price_card,totalwinners


    }




}
struct price_card : Decodable {
    let price : String
    let winners : Int
    let start_position :String
    enum CodingKeys : String, CodingKey{
        case price , winners , start_position
    }

This is the main code for parsing of the data.The error I am getting while running is Error keyNotFound(CodingKeys(stringValue: "catid", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"catid\", intValue: nil) (\"catid\").", underlyingError: nil))

func experiment1(){
           let Url = URL(string: url)
                var request = URLRequest(url: Url!)
                request.httpMethod = "POST"
            request.setValue("bearer 03a4013d77568a67c159a41f680d14f4",forHTTPHeaderField: "Authorization")
                URLSession.shared.dataTask(with: Url!){ data,response,error
                   in
                    guard error == nil else{
                                       print("some error is found",error)
                                       return
                                   }
                                guard let data = data else {
                                 return
                                   }
                    print(data)
                    do{

                       let decoder = JSONDecoder()
                        decoder.keyDecodingStrategy = .convertFromSnakeCase
                        let Main = try decoder.decode(main.self,from: data)


                        print(Main.catid)
                    }
                    catch
                        let jsonErr {
                            print("Error" , jsonErr)
                        }
                    }.resume()
        }

This is my JSON

[{
        "catname": "HOT CONTESTS",
        "catid": 4,
        "sub_title": "Call the shot quickly",
        "image": "https://mybat11.com/admin/public/images_contest_category/contest_1572688096.jpg",
        "contest": [
            {
                "id": 73,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "bplt20_2020_g27",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 1,
                "maximum_user": 100,
                "getjoinedpercentage": "1%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 77,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "bblt20_2019_g17",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 81,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "c.match.adh_vs_cm.c028d",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 85,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "c.match.ns_vs_wb.63191",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 89,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "sst20_2019_g17",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 93,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "sst20_2019_g18",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 97,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "bblt20_2019_g18",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 101,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "c.match.ch_vs_os.c6d23",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 105,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "bblt20_2019_g19",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 109,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "sst20_2019_g19",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 113,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "bplt20_2020_g29",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 117,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "bblt20_2019_g20",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 121,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "bplt20_2020_g30",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 125,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "ausnz_2019_test_03",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 129,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "c.match.wb_vs_ns.7fdc4",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            },
            {
                "id": 133,
                "name": "Win Rs.1000",
                "entryfee": 12,
                "contest_type": "Amount",
                "winning_percentage": 0,
                "win_amount": 1000,
                "matchkey": "sst20_2019_g20",
                "c_type": "classic",
                "status": 1,
                "joinedusers": 0,
                "maximum_user": 100,
                "getjoinedpercentage": "0%",
                "multi_entry": 1,
                "confirmed_challenge": 0,
                "is_running": 0,
                "is_bonus": 0,
                "bonus_percentage": 0,
                "multientry_limit": null,
                "isselected": false,
                "isselectedid": "",
                "refercode": "",
                "price_card": [
                    {
                        "price": "Rs.1000",
                        "winners": 1,
                        "start_position": "1"
                    }
                ],
                "totalwinners": 1
            }
        ]
    }
   ] 

Upvotes: 0

Views: 225

Answers (3)

Shivam Parmar
Shivam Parmar

Reputation: 1570

this is how you can decode your json ...

Alamofire.request(suggurl, method: .get, encoding: JSONEncoding.default) .responseJSON { response in
                            if response.result.isSuccess{
                                let json = response.result.value! as? [Array<Any>] ?? []
                                let first = json[0] as? [String:Any] ?? [:]

                                let catname = first["catname"] as? Any

                                let catid = first["catid"] as? Any

                                let subtitle = first["sub_title"] as? Any

                                let image = first["image"] as? Any
                                let contest = first["contest"] as? [Any] ?? []

                                for i in 0..<contest.count{
                                    let singlerecord = contest[i] as? [String:Any]
                                    let id = singlerecord?["id"] as? Any ?? ""
                                    let status = singlerecord?["status"] as? Any ?? ""
                                    // and all other elements of singlerecord do same
                                    let price_card = singlerecord?["price_card"] as? [Any] ?? []
                                    let pricecard1 = price_card[0] as? [String:Any] ?? [:]
                                    let price = pricecard1["price"] as? Any ?? ""
                                    //and all elements of price_card do same




                                }

                            }else{
                            }
                        }

I hope it will work for you ...:)

Upvotes: 0

PGDev
PGDev

Reputation: 24341

The issue is because catid has an Int value instead of String, so

let catid : String?

must be replaced with

let catid : Int?

Note:

  1. Use camel-case for naming your variables instead of snake-case, i.e. sub_title must be named subTitle instead.

  2. Also, there is no need to explicitly define enum CodingKeys if the property names are same as the keys of JSON.

So, your models must be

struct Main : Decodable {     
    let catname : String?
    let catid : Int?
    let subTitle : String?
    let image : String?
    let contest : [Contest]
}

struct Contest : Decodable {
    let id : Int
    let name : String
    let entryfee : Int
    let contestType : String
    let winningPercentage : Int
    let winAmount : Int
    let matchkey : String
    let cType : String
    let status : Int
    let joinedusers : Int
    let maximumUser : Int
    let getjoinedpercentage : String
    let multiEntry : Int
    let confirmedChallenge : Int
    let isRunning : Int
    let isBonus : Int
    let bonusPercentage : Int
    let isselected : Bool
    let isselectedid : String
    let refercode : String
    var priceCard : [PriceCard]
    let totalwinners : Int
}

struct PriceCard : Decodable {
    let price : String
    let winners : Int
    let startPosition :String
}

You can now parse the data the same way you did earlier.

Upvotes: 0

Vadim Nikolaev
Vadim Nikolaev

Reputation: 2132

  1. let catid : String? should be let catid : Int?
  2. let Main = try decoder.decode(main.self,from: data) should be let Main = try decoder.decode([main].self,from: data)

I've fixed it and everything works correctly. I'd like to recommend remove this:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let Main = try decoder.decode(main.self,from: data)
print(Main.catid)

and add just it:

let Main = try? JSONDecoder().decode([main].self, from: data)
print(Main?.first?.catid)

From my side, in addition, I recommend reading the Apple documentation about naming classes and variables.

Upvotes: 1

Related Questions