How to load that JSON on tableview? - ios

I have problem with parse json to collectionview
That is my JSON:
{
"statusCode": 200,
"message": "Список курсов",
"content": [
{
"id": 1,
"slug": "kurs-a1",
"title": "Курс А1",
"can_access": 1,
"passed": 1,
"sections": [
{
"id": 1,
"slug": "razdel-1",
"title": "Раздел 1",
"can_access": 1,
"passed": 1,
"lessons": [
{
"id": 1,
"position": 1,
"title": "Сәлемдесу",
"slug": "salemdesu",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 1
},
{
"id": 3,
"position": 2,
"title": "Танысу",
"slug": "tanysu",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 1
}
]
},
{
"id": 2,
"slug": "razdel-2",
"title": "Раздел 2",
"can_access": 1,
"passed": 0,
"lessons": [
{
"id": 4,
"position": 3,
"title": "Бұл – менің отбасым",
"slug": "bul-menin-otbasym",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 0
},
{
"id": 5,
"position": 4,
"title": "Жасы нешеде?",
"slug": "zhasy-neshede",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 1,
"passed": 0
}
]
},
{
"id": 3,
"slug": "razdel-3",
"title": "Раздел 3",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 7,
"position": 5,
"title": "Туған күн",
"slug": "tugan-kun",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 9,
"position": 6,
"title": "Құттықтау",
"slug": "kuttyktau",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 4,
"slug": "razdel-4",
"title": "Раздел 4",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 10,
"position": 7,
"title": "Адам келбеті",
"slug": "adam-kelbeti",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 12,
"position": 8,
"title": "Адамның мінез-құлқы",
"slug": "adamnyn-minez-kulky",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 5,
"slug": "razdel-5",
"title": "Раздел 5",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 13,
"position": 9,
"title": "Менің мамандығым",
"slug": "menin-mamandygym",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 15,
"position": 10,
"title": "Кім болып жұмыс істейді?",
"slug": "kim-bolyp-zhumys-istejdi",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 6,
"slug": "razdel-6",
"title": "Раздел 6",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 16,
"position": 11,
"title": "Жұмыс орны",
"slug": "zhumys-orny",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 17,
"position": 12,
"title": "Жұмыс күні",
"slug": "zhumys-kuni",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 7,
"slug": "razdel-7",
"title": "Раздел 7",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 19,
"position": 13,
"title": "Тесты ЦОР-а",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 20,
"position": 14,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 8,
"slug": "razdel-8",
"title": "Раздел 8",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 22,
"position": 15,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 23,
"position": 16,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 9,
"slug": "razdel-9",
"title": "Раздел 9",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 25,
"position": 17,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 27,
"position": 18,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 10,
"slug": "razdel-10",
"title": "Раздел 10",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 28,
"position": 19,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 29,
"position": 20,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 11,
"slug": "razdel-11",
"title": "Раздел 11",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 32,
"position": 21,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 33,
"position": 22,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
},
{
"id": 12,
"slug": "razdel-12",
"title": "Раздел 12",
"can_access": 0,
"passed": 0,
"lessons": [
{
"id": 34,
"position": 23,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
},
{
"id": 35,
"position": 24,
"title": "Тесты",
"slug": "testy",
"image": "https://tilqural.kz/assets/img/default-lesson-icon.png",
"can_access": 0,
"passed": 0
}
]
}
]
}
]
}
I decode it and i want parse it to collectionview.
How can i get content [{sections[{lessons[{title}]}]}]?
I made a request
func numberOfSections(in collectionView: UICollectionView) -> Int {
return arrData1.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let dn = arrData1[section]
let st = dn.sections?[section]
return (st?.lessons?.count)!
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "main_cell", for: indexPath) as! MainCollectionViewCell
cell.lesson_text_1.text = arrData1.first?.sections?[indexPath.item].title
// cell.lesson_img_1.image = UIImage(named: lesson_image_1[indexPath.row])
// cell.lesson_text_1.text = lesson_text_1[indexPath.row]
return cell
}
but it return 2 cell to me
But i need 24 lessons!
Thank you
Decoding
struct Welcome: Codable {
let statusCode: Int
let message: String
let content: [Content]
}
struct Content: Codable {
let id: Int
let slug, title: String
let canAccess: Int?
let passed: Int
let sections: [Content]?
let lessons: [Lesson]?
enum CodingKeys: String, CodingKey {
case id, slug, title
case canAccess = "can_access"
case passed, sections
case lessons = "lessons"
}
}
struct Lesson: Codable {
let id, position: Int
let title, slug: String
let image: String
let canAccess: Int?
let passed: Int
enum CodingKeys: String, CodingKey {
case id, position, title, slug, image
case canAccess = "can_access"
case passed
}
}
api call function
let mData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let data_new = try decoder.decode(Welcome.self, from: data)
DispatchQueue.main.async {
self.tableview.reloadData()
self.arrData1 = data_new.content
print(data_new)
}
} catch {
print("Error in CheckNew is : \n\(error)")
}
}
mData.resume()
enter image description here

Although the JSON structure is quite similar I recommend to use separate structs for Section and Lesson.
Another benefit is you get rid of all optionals
struct Welcome: Codable {
let statusCode: Int
let message: String
let content: [Content]
}
struct Content: Codable {
let id: Int
let slug, title: String
let canAccess: Int
let passed: Int
let sections: [Section]
}
struct Section: Codable {
let id: Int
let title, slug: String
let canAccess: Int
let passed: Int
let lessons: [Lesson]
}
struct Lesson: Codable {
let id, position: Int
let title, slug: String
let image: URL
let canAccess: Int
let passed: Int
}
As you are using the .convertFromSnakeCase strategy all coding keys are redundant.

Related

I am trying to create a heirarchy view. The view should expand and contract once clicked on each person

When clicked on each person , the subordinates list of that person should appear at the bottom. The whole list is dynamic .
{
"EmployeeId": "1",
"Name": "John",
"Position": "HR",
"Image": "",
"SubordinateCount": 6,
"Subordinates": [
{
"EmployeeId": "2",
"Name": "Sub john 1",
"Position": "Manager",
"Image": "",
"SubordinateCount": 1,
"Subordinates": [
{
"EmployeeId": "3",
"Name": "Joseph",
"Position": "Admin",
"Image": "",
"SubordinateCount": 1,
"Subordinates": [
{
"EmployeeId": "4",
"Name": "Raj",
"Position": "Software Developer",
"Image": "",
"SubordinateCount": 0,
"Subordinates": []
}
]
}
]
},
{
"EmployeeId": "5",
"Name": "Rahul",
"Position": "ERP Consultant",
"Image": "",
"SubordinateCount": 16,
"Subordinates": [
{
"EmployeeId": "6",
"Name": "Fam",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "7",
"Name": "Salman A Q",
"Position": "Software Developer",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "8",
"Name": "Mac",
"Position": "Software Developer",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "9",
"Name": "Mathew",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "10",
"Name": "Kim",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "11",
"Name": "Loren",
"Position": "Software Developer",
"Image": "",
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "12",
"Name": "Adam",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "13",
"Name": "Meera",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "14",
"Name": "MMM",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "15",
"Name": "Master",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "16",
"Name": "Michael",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "17",
"Name": "George",
"Position": "Consultant",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "18",
"Name": "Ahmedu A F",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "19",
"Name": "KKKK",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "20",
"Name": "xxx",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "21",
"Name": "DK",
"Position": "QA",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
}
]
},
{
"EmployeeId": "22",
"Name": "HHHH",
"Position": "Engineer",
"Image": "",
"SubordinateCount": 1,
"Subordinates": [
{
"EmployeeId": "23",
"Name": "Ar",
"Position": "Technical",
"Image": "",
"SubordinateCount": 0,
"Subordinates": []
}
]
},
{
"EmployeeId": "24",
"Name": "Sun",
"Position": "Software Developer",
"Image": null,
"SubordinateCount": 1,
"Subordinates": [
{
"EmployeeId": "25",
"Name": "AAAA",
"Position": null,
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
}
]
},
{
"EmployeeId": "26",
"Name": "CCCC",
"Position": "Consultant",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "27",
"Name": "Jaaaa",
"Position": "Software Developer",
"Image": null,
"SubordinateCount": 2,
"Subordinates": [
{
"EmployeeId": "28",
"Name": "Jay",
"Position": "Ssssss",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
},
{
"EmployeeId": "29",
"Name": "NNNN",
"Position": "Sssss",
"Image": null,
"SubordinateCount": 1,
"Subordinates": [
{
"EmployeeId": "30",
"Name": "Jo",
"Position": "Engineer",
"Image": null,
"SubordinateCount": 0,
"Subordinates": []
}
]
}
]
}
]
}
This is the json to be used .I have tried with collection view inside table view.But failed when i try to delete a row when user moves to the top and clicks on a new person . I have seen many libraries showing tree structure for table view . But i think that cannot be used here .
This is what i have tried so far.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return selectedIndexes.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var bottomCell : SubordinatesTableViewCell! = self.Extableview.dequeueReusableCell(withIdentifier: "SubordinatesTableViewCell") as? SubordinatesTableViewCell
if bottomCell == nil {
let nib:Array = Bundle.main.loadNibNamed("SubordinatesTableViewCell", owner: self, options: nil)!
bottomCell = nib[0] as? SubordinatesTableViewCell
}
bottomCell.empLevel = indexPath.row
bottomCell.delegate = self
bottomCell.subordinateDetails = self.subordinatesList
return bottomCell
}
extension CurrentVC : SubordinateCellDelegate {
func employeeClicked(row: Int?, index: Int?) {
self.subordinatesList = self.heirarchy?.subordinates
self.currentHeirarchyLevel = row! + 1
if self.Extableview.numberOfRows(inSection: 0) > row! + 1 {
var newIndexes = [Int]()
if row! == 0 {
self.selectedIndexes.removeAll()
self.selectedIndexes.append(index!)
}else {
for i in 0..<(row! + 1) {
newIndexes.append(selectedIndexes[i])
}
self.selectedIndexes = newIndexes
self.selectedIndexes.append(index!)
}
for i in 0..<row! + 1 {
self.subordinatesList = self.subordinatesList?[self.selectedIndexes[i]].subordinates
print(subordinatesList)
}
if subordinatesList?.count ?? 0 > 0 {
self.Extableview.reloadRows(at: [IndexPath(row: self.currentHeirarchyLevel, section: 0)], with: .fade)
}else {
for i in 0..<self.Extableview.numberOfRows(inSection: 0) {
if i > row! {
self.Extableview.beginUpdates()
self.Extableview.deleteRows(at: [IndexPath(row: 1, section: 0)], with: .fade)
}
}
self.numOfsections = row! + 1
self.Extableview.endUpdates()
}
}else {
self.selectedIndexes.append(index!)
for i in 0..<row! + 1 {
self.subordinatesList = self.subordinatesList?[self.selectedIndexes[i]].subordinates
}
if self.subordinatesList?.count ?? 0 > 0 {
self.Extableview.beginUpdates()
self.numOfsections = row! + 2
self.Extableview.insertRows(at: [IndexPath(row: row! + 1, section: 0)], with: .none)
self.Extableview.endUpdates()
}else {
for i in 0..<self.Extableview.numberOfRows(inSection: 0) {
if i > row! {
self.Extableview.beginUpdates()
self.numOfsections = row! + 1
self.Extableview.deleteRows(at: [IndexPath(row: 1, section: 0)], with: .fade)
}
}
self.Extableview.endUpdates()
}
}
}
}
Declare 4 variables ,
var heirarchy : Subordinates?
var numOfRows = 0
var subordinatesList : [Subordinates]?
var subList = [[Subordinates]?]()
Once you get the json response ,
self.numOfRows += 1
self.subordinatesList?.append(self.heirarchy!)
self.subList.append([self.heirarchy!])
Create a delegate function for collection view item click as below .
func employeeClicked(row: Int?, index: Int?, subordinates: [Subordinates]?) {
if (subordinates?.count ?? 0) > 0 {
self.subordinatesList = subordinates
if numOfRows > row! + 2 {
self.tableView.beginUpdates()
for i in (row! + 1)..<tableView.numberOfRows(inSection: 0) {
self.tableView.deleteRows(at: [IndexPath(row: i, section: 0)], with: .fade)
self.numOfRows = numOfRows - 1
self.subList.removeLast()
}
self.subList.append(self.subordinatesList)
self.numOfRows = row! + 2
self.tableView.insertRows(at: [IndexPath(row: row! + 1, section: 0)], with: .fade)
self.tableView.endUpdates()
}
else if numOfRows == row! + 2 {
self.subList[row! + 1] = self.subordinatesList
self.tableView.reloadRows(at: [IndexPath(row: row! + 1, section: 0)], with: .fade)
}else {
self.subList.append(self.subordinatesList)
self.numOfRows = row! + 2
self.tableView.insertRows(at: [IndexPath(row: row! + 1, section: 0)], with: .fade)
}
}else {
if numOfRows > row! + 1 {
self.tableView.beginUpdates()
for i in (row! + 1)..<tableView.numberOfRows(inSection: 0) {
self.tableView.deleteRows(at: [IndexPath(row: i, section: 0)], with: .fade)
self.numOfRows = numOfRows - 1
self.subList.removeLast()
}
self.tableView.endUpdates()
}
}
self.tableView.scrollToBottom()
}
}
In tableview cellfor row delegate use the value of sublist array.
Hope this helps you . I checked the code and it is working fine for me.

Binding JSON data to TableView and CollectionView

I am trying to create a table view with a collection view in each cell. My JSON structure is like Main Menu title for the tv cell and in each main object, I receive a submenu, whose data I want to use in the collection view.
The issue I am facing is in using indexes of table cell and collection cell to get the nested data. Here is my JSON
"MainMenu": [
{
"ID": 8,
"MasterID": 12,
"Title": "Payment",
"Image": "image.png",
"SubMenu": [
{
"ID": 9,
"Title": "My Bill",
"Image": "image.png"
},
{
"ID": 10,
"Title": "Electricity ",
"Image": "image.png"
},
{
"ID": 11,
"Title": "Gas",
"Image": "image.png"
},
{
"ID": 12,
"Title": "Telephone",
"Image": "image.png"
},
{
"ID": 13,
"Title": "Water",
"Image": "image.png"
}
]
},
{
"ID": 40,
"MasterID": 14,
"Title": "Services",
"Image": "image.png",
"SubMenu": [
{
"ID": 32,
"Title": "Upload Slip",
"Image": "image.png"
},
{
"ID": 41,
"Title": "SRY (Self Reliant Youth)",
"Image": "image.png"
},
{
"ID": 42,
"Title": "Dollor Product Purchase ",
"Image": "image.png"
},
{
"ID": 43,
"Title": "ARY Coin Redemption",
"Image": "image.png"
},
{
"ID": 44,
"Title": "Pay Via QR",
"Image": "image.png"
},
{
"ID": 45,
"Title": "Card Request",
"Image": "image.png"
}
]
},
{
"ID": 14,
"MasterID": 8,
"Title": "Mobile Balance",
"Image": "image.png",
"SubMenu": [
{
"ID": 15,
"Title": "My Mobile",
"Image": "image.png"
},
{
"ID": 16,
"Title": "Mobilink",
"Image": "image.png"
},
{
"ID": 17,
"Title": "Telenor",
"Image": "image.png"
},
{
"ID": 18,
"Title": "Ufone",
"Image": "image.png"
},
{
"ID": 19,
"Title": "Warid",
"Image": "image.png"
},
{
"ID": 20,
"Title": "Zong",
"Image": "image.png"
}
]
},
{
"ID": 46,
"MasterID": 6,
"Title": "Help",
"Image": "image.png",
"SubMenu": [
{
"ID": 47,
"Title": "Call",
"Image": "image.png"
},
{
"ID": 48,
"Title": "Chat",
"Image": "image.png"
},
{
"ID": 49,
"Title": "Email",
"Image": "image.png"
},
{
"ID": 50,
"Title": "Others",
"Image": "image.png"
},
{
"ID": 51,
"Title": "VAS / SMS",
"Image": "image.png"
}
]
},
{
"ID": 21,
"MasterID": 5,
"Title": "Fund Transfer",
"Image": "image.png",
"SubMenu": [
{
"ID": 22,
"Title": "To Other ARY Wallet",
"Image": "image.png"
},
{
"ID": 23,
"Title": "To Bank Account",
"Image": "image.png"
}
]
},
{
"ID": 34,
"MasterID": 1,
"Title": "$ & MilliGold Deal",
"Image": "image.png",
"SubMenu": [
{
"ID": 35,
"Title": "$ Deposit",
"Image": "image.png"
},
{
"ID": 36,
"Title": "$ Purchase",
"Image": "image.png"
},
{
"ID": 37,
"Title": "$ Time Games",
"Image": "image.png"
},
{
"ID": 38,
"Title": "Scan for Bid",
"Image": "image.png"
}
]
}
],
"CustomerAccountInformation": []
}
Please guide me how can I use my JSON objects each in different tablecell.
Here is what I have tried:
TVCell
cell.titleLabel.text = menu?.mainMenu?[indexPath.row].title ?? "Our services"
CollectionCell
cell.image.af_setImage(withURL: URL.init(string: (menu?.mainMenu?[indexPath.row].subMenu?[indexPath.row].image)!)!)
First, in your tableview cell, set the tag of the collectionview to indexPath.row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : TVCell = tableview.dequeueReusableCell(withIdentifier: "TVCell", for: indexPath) as! TVCell
cell.myCollectionView.tag = indexPath.row
return cell
}
Now in your collectionview cell you can parse the data like following
let index = cell.tag
cell.image.af_setImage(withURL: URL.init(string: (menu?.mainMenu?[index].subMenu?[indexPath.row].image)!)!)

Convert Array<CustomObject> to JSON

I hava a problem I can't convert array to JSON in SWIFT 3.0 . I am using ObjectMapper
My object
class OrderItem: Mappable {
required init?(map: Map) {
}
init() {
}
var oi_id: Int? = 0
var quantity: Double? = 0.0
var discount: Double = 0.0
var sku: Int? = 0
var orderId: Int? = 0
var Product: Product?
var isAdd: Bool = false
var isMissing: Bool!
func mapping(map: Map) {
oi_id <- map["oi_id"]
quantity <- map["quantity"]
discount <- map["discount"]
orderId <- map["orderId"]
Product <- map["Product"]
isAdd <- map["isAdd"]
isMissing <- map["isMissing"]
}}
Convert/ generating the result JSON :
var jsonArrayOrderItem = arrayOrderItem.toJSON()
Result JSON after convert . JSON is wrong :(
[["oi_id": 0, "isAdd": false, "quantity": 1.0, "Product": ["isHot": false, "discount": 50.0, "description": "description", "Acronym": "kg", "priceWithDiscount": 0.62, "bigValue": 1.0, "sku": 14, "Name": "Green Apples", "Price": 1.23, "IsFavorite": true, "smallValue": 0.20000000000000001, "Category": ["bigImageUrl": "https://i.imgur.com/7R3sFnP.png", "ImageUrl": "https://i.imgur.com/NJP4CuA.png", "cat_id": 11, "Name": "Fruits & vegetables", "Products": []], "MeasurementUnitId": 0, "ImageUrl": "https://s22.postimg.org/5992ux3j5/Green_apples.jpg", "CategoryId": 11, "Brand": ["brand_id": 8, "name": "Arbella", "imageUrl": "http://i.imgur.com/xx5ZAgL.jpg", "Products": []]], "orderId": 0, "discount": 0.0], ["oi_id": 0, "isAdd": false, "quantity": 1.0, "Product": ["isHot": false, "discount": 50.0, "description": "description", "Acronym": "kg", "priceWithDiscount": 0.62, "bigValue": 1.0, "sku": 17, "Name": "Mango", "Price": 1.23, "IsFavorite": true, "smallValue": 0.20000000000000001, "Category": ["bigImageUrl": "https://i.imgur.com/7R3sFnP.png", "ImageUrl": "https://i.imgur.com/NJP4CuA.png", "cat_id": 11, "Name": "Fruits & vegetables", "Products": []], "MeasurementUnitId": 0, "ImageUrl": "https://s22.postimg.org/4om6zb2zl/Mango.jpg", "CategoryId": 11, "Brand": ["brand_id": 8, "name": "Arbella", "imageUrl": "http://i.imgur.com/xx5ZAgL.jpg", "Products": []]], "orderId": 0, "discount": 0.0]]
try for Swift 4.0 - It has inbuilt JSONDecoder.

SwiftyJSON Item At Index Not Working

I have the following dummy JSON data:
{
"folder": {
"id": 1,
"name": "Home",
"parent_folder_id": null,
"num_of_items": 10,
"num_of_items_complete": 10,
"children": {
"folders": [
{
"id": 2,
"name": "Identification",
"num_of_items": 4,
"num_complete": 4
},
{
"id": 3,
"name": "House and Household Equipment",
"num_of_items": 6,
"num_complete": 2
},
{
"id": 4,
"name": "Insurance",
"num_of_items": 4,
"num_complete": 3
},
{
"id": 5,
"name": "Owned Items",
"num_of_items": 6,
"num_complete": 5
}
],
"input_fields": [
{
"id": 1,
"key": "Something",
"value": "Dark Side",
"type": "text"
}
],
"shortcuts": [
]
}
}
}
And I need to access each child in "children" with an INDEX rather than by it's NAME for a collectionView:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.data["folder"]["children"][section].count
}
But it always returns 0 for the count. Is there anyway I can do this?
Try with this:
return self.data["folder"]["children"]["folders"].count
I think is the only way you can do it.

Count ocurrence of two fields

I have this kind of documents in a MongoDb collection:
[
{
"_id": {
"id": 892,
"answer": "C",
"level": "regular"
},
"total": 4
},
{
"_id": {
"id": 891,
"answer": "Regular",
"level": "neutral"
},
"total": 3
},
{
"_id": {
"id": 892,
"answer": "B",
"level": "regular"
},
"total": 3
},
{
"_id": {
"id": 891,
"answer": "Ótimo",
"level": "positive"
},
"total": 5
},
{
"_id": {
"id": 892,
"answer": "E",
"level": "regular"
},
"total": 3
},
{
"_id": {
"id": 891,
"answer": "Bom",
"level": "positive"
},
"total": 1
},
{
"_id": {
"id": 891,
"answer": "Ruim",
"level": "negative"
},
"total": 2
},
{
"_id": {
"id": 892,
"answer": "D",
"level": "regular"
},
"total": 3
},
{
"_id": {
"id": 891,
"answer": "Péssimo",
"level": "negative"
},
"total": 3
},
{
"_id": {
"id": 892,
"answer": "F",
"level": "regular"
},
"total": 1
}
]
I'm trying to count answer and level ocurrences using MongoDb aggregation pipiline. I'm expecting some output like this:
[
{
"id": 891,
"answers": [
{
"answer": "Ótimo",
"count": 5
},
{
"answer": "Bom",
"count": 1
},
{
"answer": "Regular",
"count": 3
},
{
"answer": "Ruim",
"count": 2
},
{
"answer": "Péssimo",
"count": 3
}
],
"levels": [
{
"level": "positive",
"count": 6
},
{
"level": "neutral",
"count": 3
},
{
"level": "negative",
"count": 5
}
],
"total": 14
},
{
"id": 892,
"answers": [
{
"answer": "B",
"count": 3
},
{
"answer": "C",
"count": 4
},
{
"answer": "D",
"count": 3
},
{
"answer": "E",
"count": 3
},
{
"answer": "F",
"count": 1
},
],
"levels": [
{
"level": "regular",
"count": 14
}
],
"total": 14
}
]
How could I achieve the desired output using MongoDb aggregation pipeline?
EDIT: Actually I'm already using $group to achieve something like that, but I guess only one $group step on the pipeline will not achieve the desired output. Here is my current $group step:
{
$group: {
_id: {
id: "$_id.id"
},
answers: {
$push: {
answer: "$_id.answer",
count: "$count"
}
},
levels: {
$push: {
level: "$_id.level",
count: "$count"
}
},
total: { $sum: "$count" }
}
}
Here is the output I have so far:
[
{
"_id": {
"id": 892
},
"answers": [
{
"answer": "F",
"count": 1
},
{
"answer": "D",
"count": 3
},
{
"answer": "E",
"count": 3
},
{
"answer": "C",
"count": 4
},
{
"answer": "B",
"count": 3
}
],
"levels": [
{
"level": "regular"
},
{
"level": "regular"
},
{
"level": "regular"
},
{
"level": "regular"
},
{
"level": "regular"
}
]
},
{
"_id": {
"id": 891
},
"answers": [
{
"answer": "Ruim",
"count": 2
},
{
"answer": "Péssimo",
"count": 3
},
{
"answer": "Bom",
"count": 1
},
{
"answer": "Regular",
"count": 3
},
{
"answer": "Ótimo",
"count": 5
}
],
"levels": [
{
"level": "negative"
},
{
"level": "negative"
},
{
"level": "positive"
},
{
"level": "neutral"
},
{
"level": "positive"
}
]
}
]
The following aggregation pipeline:
{ $group: {
_id: { id: "$_id.id" },
answers: {
$push: {
answer: "$_id.answer",
level: "$_id.level",
count: "$total"
}
},
levels: {
$push: {
level: "$_id.level",
count: "$total"
}
}
}},
{ $unwind: $levels },
{ $group: {
_id: {
id: "$_id.id",
level: "$levels.level"
},
answers: { $addToSet: "$answers" },
total: { $sum: "$levels.count" }
}},
{ $group: {
_id: { id: "$_id.id" },
answers: { $addToSet: "$answers" },
levels: {
$push: {
level: "$_id.level",
count: "$total"
}
},
total: { $sum: "$total" }
}},
{ $project: {
_id: 0,
id: "$_id.id",
answers: 1,
levels: 1,
total: 1
}}
Will produce the desired output.

Resources