amp.dev
amp.dev

Reputation: 470

How to parse JSON dictionary using SwiftyJSON and Alamofire

I have a problem with my alamofire.request. I tried to to decode JSON response with Struct using SwiftyJSON. . But my model data is getting nil.

here is my API response

 {
 "userDetails" : 
  { "id":2,
    "roleID":1,
    "successFlag":1
  },
  "settingID" : "20"
 }

Model class

import Foundation
import SwiftyJSON


struct User {
    var settingID : String?
    var userdetails : UserDetails?

      init(json : JSON?) {

         self.settingID = json?["settingID"].string
         if let value = json?["userDetails"].dictionaryObject {

            let new = UserDetails(json: JSON(value))
             self.userdetails = new
          }
        }

       }

   struct UserDetails  {

      var id : Int?
      var roleID : Int?
      var successFlag : Int?

        init(json : JSON?) {

             self.id = json?["id"].int
             self.roleID = json?["roleID"].int
             self.successFlag = json?["successFlag"].int

        }

      }

My code for Data fetching using Alamofire and SwiftyJSON

    import Alamofire
    import SwiftyJSON


     var userData : [User] = []

     func fetchData() {

     Alamofire.request(base_url + APIManager.loginApi, method: .post, parameters:      params, encoding: URLEncoding.queryString, headers: nil).responseJSON { (resp) in

            switch resp.result {

            case .success :
                print(resp.result)

                do {

                    let myResult = try JSON(data: resp.data!)
                    print(myResult)

                    myResult.dictionaryValue.forEach({(user) in

                        let newUser = User(json: JSON(user))
                        self.userData.append(newUser)

                        print(self.userData)
                    })


                }catch {
                    print(error)
                }

                break

            case .failure :
                break
            }
        }

      }

But if i print self.userData , getting nill response. Have you any idea why I can't decode my struct with my JSON data?.

Thanks a lot for your help

Upvotes: 1

Views: 1433

Answers (2)

MBT
MBT

Reputation: 1391

Change your response code like below

switch response.result {
case .success(let value):
    let response = JSON(value)
    print("Response JSON: \(response)")

    let newUser = User(json: response)
    self.userData.append(newUser)
    print(self.userData)

case .failure(let error):
    print(error)
    break
}

Upvotes: 1

PGDev
PGDev

Reputation: 24341

Try using Codable instead. It is easier to create a Codable model and is Apple recommended.

struct Root: Decodable {
    let userDetails: User
    let settingID: String

}

struct User: Decodable {
    let id: Int
    let roleID: Int
    let successFlag: Int
}

Parse the data like,

do {
    let response = try JSONDecoder().decode(Root.self, from: data)
    print(response)
} catch {
    print(error)
}

Upvotes: 3

Related Questions