0

I am trying to validated students == null or values avilable, If values avilable I need to get grade and store grade into table data array and subject null also I need to store in same array For example: [10, null, 11] from below JSON. how to append like this in single array from JSON response.

    {  
   "students":[  
      {  
         "id":0,
         "subject":[  
            {  
               "grade":10
            }
         ]
      },
      {  
         "id":1,
         "subject":null
      },
      {  
         "id":2,
         "subject":[  
            {  
               "grade":11
            }
         ]
      }
   ]
}

Expected output: [10,null,11,......] //This array I am going to use Tableview cell

I am validating based on null and not null array values within cell for row. I can use var array = [String?] for accepting null values but how to append two different field result into same array?

3 Answers 3

1

You should take a look into the 'Codable' protocol.

By simply defining a struct like:

struct Student: Codable

you can decode it from JSON into these objects.

See for example: hackernoon or grokswift

Sign up to request clarification or add additional context in comments.

2 Comments

I have done many lines of codes without Struct, now timeline is ended So unable to change entire JSON. So Please let me know some other way @Simon
could you please provide some alternative? I have updated my post.
0

This looks like a trivial scenario. Best solution is Decodable. Your payload loaded from network or whatever will be parsed into structure. Now you can easily make any manipulations.

Setup: Open a new project. Add "payload.json" file with json payload you provided in question. Add the following to your project.

import UIKit

struct StudentData: Decodable {
    var students: [Student]
}

struct Student: Decodable {
    var id: Int
    var subject: [Subject]?
}

struct Subject: Decodable {
    var grade: Int
}

class ViewController: UIViewController {

    var data: Data? {
        guard let path = Bundle(for: type(of: self)).path(forResource: "payload", ofType: "json") else { return nil }
        return try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if let data = data {
            do {
                let studentData = try JSONDecoder().decode(StudentData.self, from: data)
                print(studentData)

               // manipulate the structure in any way you want

               let subjects: [Subject?] = studentData.students.map { $0.subject?.first }
               print(subjects)

               let nonNilValues = subjects.compactMap { $0 }
               print(subjects)

               // ... etc

            } catch let error {
                print(error.localizedDescription)
            }
        }
    }
}

Sorry for not coding in playgrounds. It's way too buggy.

5 Comments

I am getting output [Optional(test.Subject(grade: 10)), nil, Optional(test.Subject(grade: 11))] is there anything other way except Decodable because I used normal JSON parsing and storing separate array@Oleh Zayats
@JUJU I advise you to understand whats going on in the code. Copy it. Play with it. 'subjects' var from my snippet is a structure of type '[Subject?]', it will produce '[Optional(Subject(grade: 10), nil, Optional(Subject(grade: 11))]', after you can extract values from array.
Sure I understand but I implemented many lines by using old method of JSON parse, So unable to alter the old to decode pattern. Could you please post how to extract '[Optional(Subject(grade: 10), nil, Optional(Subject(grade: 11))]' to [10,null,11] @Oleh Zayats
@JUJU looks like a great opportunity for refactoring isn't it? :) Codable protocol makes decoding much easier, safer and readable. If you want to parse json the old way you should provide more data I guess. Try to investigate. It's not hard to move you're code to Codable in several steps. If this is not your case then provide more info in question (what's the current implementation is).
Yes i agree I will rework on it btw dead line I reached so need to submit quickly for temporary I need to append two values like subject and subject.grade values like [10,null,11,......] into single table data array. Based on that array table cell index know which index value available and which one is null.@Oleh Zayatz
0

Try this

 let students = [["id": 0,"subject": [["grade": 10]]],
                    ["id": 0,"subject": nil],
                    ["id": 0,"subject": [["grade": 10]]]] as! [Dictionary<String,Any>]

 let array = students.map({(($0["subject"] as? [Any])?.first as? Dictionary<String,Int>)?["grade"]})
 print(array)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.