1

I have a class with some variables and I want to create an array of objects of this class by parsing the JSON output using SwiftyJSON(I'm new to SwiftyJSON and so facing some problem while creating one) and display them using a Table

Can someone help me in creating the array of custom class objects.

My Model class:

    class RankDetailsModel
    {
        var key:String!
        var currentMonthRank: Int!
        var currentRevenue:Double!
        var lastMonthRank:Int!
        var lastMonthRevenue:Double!

        init?(rank: [String: Any]) {

            guard let key = rank["Key"] as? String,
            let currentMonthRank = rank["CurrentMonthRank"] as? Int,
            let currentRevenue = rank["CurrentRevenue"] as? Int,
            let lastMonthRank = rank["LastMonthRank"] as? String,
            let lastMonthRevenue = rank["LastMonthRevenue"] as? String
                else{
                    return nil
            }

            self.key = key;
        self.currentMonthRank = currentMonthRank;
        self.currentRevenue = Double(currentRevenue);
        self.lastMonthRank = Int(lastMonthRank);
        self.lastMonthRevenue = Double(lastMonthRevenue);
        }
    }

JSON response:

{ "AfxRank":
    [{
        "CurrentMonthRank" : 1,
        "Key" : "WSM",
        "CurrentRevenue" : 28834854,
        "LastMonthRevenue": null,
        "LastMonthRank": null
      },
      {
        "CurrentMonthRank" : 2,
        "Key" : "SAM",
        "CurrentRevenue" : 21880000,
        "LastMonthRevenue": null,
        "LastMonthRank": null
      },
      {
        "CurrentMonthRank" : 3,
        "Key" : "CI",
        "CurrentRevenue" : 11380000,
        "LastMonthRevenue": null,
        "LastMonthRank": null
      }]
}

My Code in VC:

var rankArray : [RankDetailsModel] = []
switch(response.result) {
                case .success(_):
                    if let data = response.result.value{

                        let jsonD = JSON(data) 
                        let dataNew = jsonD.rawString()?.data(using: String.Encoding.utf8) 
                        let jsonFinal = JSON(dataNew)
                        print(jsonFinal["AfxRank"]) //successfully printing the json array as shown above
                        rankArray = jsonFinal["AfxRank"].arrayValue as! [RankDetailsModel] //throwing an error 'RankDetailsModel' is not a subtype of JSON

//can I try something like this. (I didnt use SwifyJson and Alamofire in this case)
//if let userDict = json["AfxRank"] as? [String:Any]
//                        {
//                            guard let userObject = //RankDetailsModel(rank:userDict) else {
//                                print("Failed to create user from //dictionary")
//                                return
//                            }   
                    }
                    break

                case .failure(_):
                    print(response.result.error)
                    break

                }
2
  • You ultimately need to loop through JSON array, passing data from each parsed object into your model’s initializer. Did you try the approach you mention in the comment? Commented Dec 12, 2016 at 3:23
  • @Tony I tried converting it to dictionary as in comments. But it is throwing an error saying JSON doesnt have any member like [String:Any]. Will try again and update the correct error message Commented Dec 12, 2016 at 3:33

1 Answer 1

1

Your key AfxRank contains Array not dictionary so you need to type cast it to [[String:Any]], then go through the loop and append the object in array of [RankDetailsModel].

var rankArray = [RankDetailsModel]()
if let userArray = json["AfxRank"].arrayValue as? [[String:Any]] {
    for dic in userArray {
        if let rankDetailObj = RankDetailsModel(rank: dic) {
            rankArray.append(rankDetailObj)
        }
    }
}
Sign up to request clarification or add additional context in comments.

11 Comments

hi Nirav. When I used your code it is showing a warning near if let userArray = json["AfxRank"] as? [[String:Any]] { - cast from JSON to unrelated type [[String:Any]] always fail. When I run the code, its not going inside the if condition and just exiting.
[String:Any] is not a subtype of JSON error near that line :(
I tried using if let userArray = json["AfxRank"].arrayObject as? [[String:Any]] { and its showing no error. But then it is not satisfying the condition if let rankDetailObj = RankDetailsModel(rank: dic) { and coming out of if condition without going in.
@ASN Inside your init method before guard statement try to print your rank dictionary and check is it printing correctly?
@ASN May be problem is in this line let currentRevenue = rank["CurrentRevenue"] as? Double use as? Int then covert you int to Double.
|

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.