1

I am new here and I am parsing json which is array in side array so I can't understand how get inside array from json let me show you my json.

JSON

{
    "subject_list" =     (
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 4;
            "sub_list" =             (
                                {
                    "ch_id" = 17;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1530600693.jpg";
                    "ch_name" = " 01. Measurement";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 4;
                },
                                {
                    "ch_id" = 23;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1451930609.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 4;
                },
                                {
                    "ch_id" = 24;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1884777188.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 4;
                },
                                {
                    "ch_id" = 25;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1518702048.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 4;
                }
            );
            "sub_name" = Physics;
        },
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 8;
            "sub_list" =             (
                                {
                    "ch_id" = 26;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1437196139.jpg";
                    "ch_name" = " 1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 8;
                },
                                {
                    "ch_id" = 27;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1903171865.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 8;
                }
            );
            "sub_name" = Chemistry;
        },
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 9;
            "sub_list" =             (
                                {
                    "ch_id" = 31;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1319333294.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 9;
                }
            );
            "sub_name" = Testing;
        },
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 10;
            "sub_list" =             (
                                {
                    "ch_id" = 28;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1373218664.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 10;
                }
            );
            "sub_name" = "Test Subject";
        },
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 11;
            "sub_list" =             (
                                {
                    "ch_id" = 29;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/246189282.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 11;
                }
            );
            "sub_name" = "Test Subject 1";
        },
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 12;
            "sub_list" =             (
                                {
                    "ch_id" = 30;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1342731807.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 12;
                }
            );
            "sub_name" = "Test Subject 2";
        }
    );

this is my JSON and I want sub_list array from subject_list I have done some code let me show you.

CODE

func callSubChapAPI(){
        let preferences = UserDefaults.standard
        let studentlvl = "student_lvl"
        let student_lvl = preferences.object(forKey: studentlvl) as! String
        print(student_lvl)
        let params = ["level_id": student_lvl]
        Alamofire.request(subListWithChapter, method: .post, parameters: params).responseJSON(completionHandler: {(response) in
            switch response.result{
            case.success(let data):
                print(data)

                let json  = JSON(data)
                print(json)
                do {
                    let decoder = JSONDecoder()
                    decoder.keyDecodingStrategy = .convertFromSnakeCase
                    let subjects = try decoder.decode(SubjectResponse.self, from: data as! Data)
                    print(subjects)
                } catch {
                    print(error)
                }
            case.failure(let error):
                print(error.localizedDescription)
            }

        })
    }

here is my struct:

struct sub_list {
    let ch_id : Int
    let ch_image: String
    let ch_name: String
    let con_id: String
    let level_id: String
    let sub_id: String
}

Please see my code and json format please tell me how to get sub_list array from json please hell me and thanks in advance.

Vishal Parmar
  • 615
  • 4
  • 31

1 Answers1

0

Actually subject_list is also an array so you need to iterate that as well.

let data = json["subject_list"]
print(data)
data.array?.forEach({ (subject) in
     subject["sub_list"].array?.forEach({ (chapList) in
           let chapter = sub_list(ch_id: chapList["ch_id"].intValue, ch_image: chapList["ch_image"].stringValue, ch_name: chapList["ch_name"].stringValue, con_id: chapList["con_id"].stringValue, level_id: chapList["level_id"].stringValue, sub_id: chapList["sub_id"].stringValue)
           print(chapter)
           self.chapListData.append(chapter)
     })
})

self.collView.reloadData()

Recommendation

It's not worth adding any dependency for json parsing when you already have Apple provided Codable. It will reduce much of your boilerplate code added because of SwiftyJSON.

Below is a complete example for your current api,

struct SubjectResponse: Decodable {
    let subjectList: [Subject]
}

struct Subject: Decodable {
    let subList: [Chapter]
}

struct Chapter: Decodable {
    let chId : Int
    let chImage: String
    let chName: String
    let conId: Int
    let levelId: Int
    let subId: Int
}

Alamofire.request(subListWithChapter, method: .post, parameters: params).responseData() { (response) in
    switch response.result {
    case .success(let data):
        do {
            let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            let subjects = try decoder.decode(SubjectResponse.self, from: data)
            print(subjects)
        } catch {
            print(error)
        }
    case .failure(let error):
        print(error.localizedDescription)
    }
}
Kamran
  • 14,987
  • 4
  • 33
  • 51
  • when i put your code so for data it giving suggestion like this Cannot convert value of type 'Any' to expected argument type 'Data' and when i insert as! its giving me crash Data – Vishal Parmar Dec 18 '18 at 06:51
  • Error is like : Could not cast value of type '__NSSingleEntryDictionaryI' (0x1c6c8dcc0) to 'NSData' (0x1c6c8ddd8). 2018-12-18 12:22:13.912859+0530 XMEducation[5496:1296891] Could not cast value of type '__NSSingleEntryDictionaryI' (0x1c6c8dcc0) to 'NSData' (0x1c6c8ddd8). – Vishal Parmar Dec 18 '18 at 06:52
  • You must be using `.responseJSON` while you have to use `responseData()`. Copy the complete example. – Kamran Dec 18 '18 at 06:53
  • i copied but still its giving me issue – Vishal Parmar Dec 18 '18 at 06:55
  • You are using wrong method here `Alamofire.request(subListWithChapter, method: .post, parameters: params).responseJSON`. Just copy the whole example i provided above. – Kamran Dec 18 '18 at 07:03
  • Yes its working now please help me last that how to set image url in imageview which in side collection view from response please – Vishal Parmar Dec 18 '18 at 07:09
  • please help me how to populate image from SubjectResponse to Collectionview – Vishal Parmar Dec 18 '18 at 07:13
  • That is a different question. But its has already been asked multiple time. Check [this](https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift) question and in my opinion you should use `Jack` or `Leo Dabus` answers that has extensions on `UIImageView`. – Kamran Dec 18 '18 at 07:15
  • Please don't ask different questions here. You can post as separate questions. Also if the above answer helped, please mark it as an accepted answer. – Kamran Dec 18 '18 at 07:16
  • Yes but i want to ask is that how can i get only image url from whole data – Vishal Parmar Dec 18 '18 at 07:16
  • You can get all the urls as this `let urls = subjects.subjectList.map({ $0.subList.map({ $0.chImage}) }).reduce([], +)` – Kamran Dec 18 '18 at 07:21