Search code examples
iosjsonswiftalamofireswifty-json

issue while fetch data from nested json array


I am fetch JSON data from API and I am getting response successfully but there are some issue for me that how to get direct value without key first let me show you my response

Reponse

{
  "message": "Notification Sent Successfully.",
  "success": "1",
  "message_list": [
    {
      "+919722552298": [
        {
          "body": "Sent from your Twilio trial account - This is test message by purvesh",
          "from": "",
          "sid": "",
          "status": "sent",
          "date_updated": "Mon, 01 Jul 2019 12:58:49 +0000",
          "date_sent": "Mon, 01 Jul 2019 12:58:49 +0000",
          "date_created": "Mon, 01 Jul 2019 12:58:49 +0000",
          "to": ""
        },
        {
          "body": "Sent from your Twilio trial account - This is test message by purvesh",
          "from": "",
          "sid": "",
          "status": "sent",
          "date_updated": "Sat, 29 Jun 2019 09:36:07 +0000",
          "date_sent": "Sat, 29 Jun 2019 09:36:07 +0000",
          "date_created": "Sat, 29 Jun 2019 09:36:07 +0000",
          "to": ""
        },
        {
          "body": "Sent from your Twilio trial account - This is test message by purvesh",
          "from": "",
          "sid": "",
          "status": "sent",
          "date_updated": "Sat, 29 Jun 2019 09:35:18 +0000",
          "date_sent": "Sat, 29 Jun 2019 09:35:18 +0000",
          "date_created": "Sat, 29 Jun 2019 09:35:18 +0000",
          "to": ""
        },
        {
          "body": "Sent from your Twilio trial account - This is a test message...",
          "from": "",
          "sid": "",
          "status": "sent",
          "date_updated": "Sat, 29 Jun 2019 05:56:43 +0000",
          "date_sent": "Sat, 29 Jun 2019 05:56:43 +0000",
          "date_created": "Sat, 29 Jun 2019 05:56:43 +0000",
          "to": ""
        },
        {
          "body": "Sent from your Twilio trial account - This is a test...",
          "from": "",
          "sid": "",
          "status": "sent",
          "date_sent": "Thu, 27 Jun 2019 11:52:44 +0000",
          "date_created": "Thu, 27 Jun 2019 11:52:43 +0000",
          "date_updated": "Thu, 27 Jun 2019 11:52:44 +0000",
          "to": ""
        }
      ]
    },
    {
      "+61459036405": [
        {
          "body": "Sent from your Twilio trial account - Thanks for the message. Configure your number's SMS URL to change this message.Reply HELP for help.Reply STOP to unsubscribe.Msg&Data rates may apply.",
          "from": "",
          "sid": "",
          "status": "delivered",
          "date_sent": "Sat, 29 Jun 2019 06:25:33 +0000",
          "date_created": "Sat, 29 Jun 2019 06:25:33 +0000",
          "date_updated": "Sat, 29 Jun 2019 06:25:35 +0000",
          "to": ""
        },
        {
          "body": "Hello Ron ",
          "from": "",
          "sid": "",
          "status": "received",
          "date_sent": "Sat, 29 Jun 2019 06:25:33 +0000",
          "date_created": "Sat, 29 Jun 2019 06:25:33 +0000",
          "date_updated": "Sat, 29 Jun 2019 06:25:33 +0000",
          "to": ""
        },
        {
          "body": "Sent from your Twilio trial account - This is a test message...",
          "from": "",
          "sid": "",
          "date_updated": "Sat, 29 Jun 2019 06:08:42 +0000",
          "date_created": "Sat, 29 Jun 2019 06:08:42 +0000",
          "status": "sent",
          "date_sent": "Sat, 29 Jun 2019 06:08:42 +0000",
          "to": ""
        }
      ]
    },
    {
      "+918733009842": [
        {
          "body": "Sent from your Twilio trial account - This is a test...",
          "from": "",
          "sid": "",
          "date_updated": "Thu, 27 Jun 2019 12:32:45 +0000",
          "date_created": "Thu, 27 Jun 2019 12:32:45 +0000",
          "status": "sent",
          "date_sent": "Thu, 27 Jun 2019 12:32:45 +0000",
          "to": ""
        },
        {
          "body": "Sent from your Twilio trial account - This is a test...",
          "from": "",
          "sid": "",
          "status": "sent",
          "date_created": "Thu, 27 Jun 2019 12:25:37 +0000",
          "date_updated": "Thu, 27 Jun 2019 12:25:37 +0000",
          "date_sent": "Thu, 27 Jun 2019 12:25:37 +0000",
          "to": ""
        },
        {
          "body": "Sent from your Twilio trial account - This is a test...",
          "from": "",
          "sid": "",
          "status": "sent",
          "date_created": "Thu, 27 Jun 2019 12:07:04 +0000",
          "date_updated": "Thu, 27 Jun 2019 12:07:04 +0000",
          "date_sent": "Thu, 27 Jun 2019 12:07:04 +0000",
          "to": ""
        },
        {
          "body": "Sent from your Twilio trial account - This is a test...",
          "from": "",
          "sid": "",
          "status": "sent",
          "date_created": "Thu, 27 Jun 2019 12:01:55 +0000",
          "date_updated": "Thu, 27 Jun 2019 12:01:55 +0000",
          "date_sent": "Thu, 27 Jun 2019 12:01:55 +0000",
          "to": ""
        }
      ]
    }
  ]
}

here is my response and now I will show you I am getting data of message_list array successfully but issue is how to get phone number which is main array as you show in my response I want numbers list which is array in side message list array

func messageListAPI(){

    let preferences = UserDefaults.standard
    let uid = "u_id"
    let acTkn = "acc_tkn"
    let u_ID = preferences.object(forKey: uid)
    let A_Token = preferences.object(forKey: acTkn)

    let params = ["user_id": u_ID!,"access_token": A_Token!,"twilio_number": "+13344313181"]
    // print(params)
    Alamofire.request(messagelist, method: .post, parameters: params).responseJSON(completionHandler: {(response) in
        switch response.result{
        case.success(let value):
            let json  = JSON(value)
            print(json)
            let message = json["message"].stringValue
            let success = json["success"].stringValue
            let data = json["message_list"]
            let model = ResponseModel(message: message, success: success, messageList: data) // Here i am getting error
        case.failure(let error):
            print(error.localizedDescription)
        }

    })
}

Here is my API call method I am getting message_list successfully can any one help me to get numbers list


Solution

  • You should create these models for response:

    /// Main response model
    struct ResponseModel: Codable {
        let message: String
        let success: String
        let messageList: [[String: [MessageList]]]
    
        enum CodingKeys: String, CodingKey {
            case message, success
            case messageList = "message_list"
        }
    }
    
    /// MessageList Model
    struct MessageList: Codable {
        let body: String
        let from: String
        let sid: String
        let status: Status
        let dateSent: String
        let dateCreated
        let dateUpdated
        let to: String
    
        enum CodingKeys: String, CodingKey {
            case body, from, sid, status
            case dateSent = "date_sent"
            case dateCreated = "date_created"
            case dateUpdated = "date_updated"
            case to
        }
    }
    
    /// For status field
    enum Status: String, Codable {
        case delivered = "delivered"
        case received = "received"
        case sent = "sent"
    }
    

    You can use these models with Alamofire

    /// YOU MUST CHANGE 'ResponseType' with the real type of response
    
    func messageListAPI(_ completion: @escaping (ResponseType) -> Void) {
        let urlString = "http://yourUrl"
        Alamofire.request(urlString).response { response in
            guard let data = response.data else { return }
            do {
                let decoder = JSONDecoder()
                let response: ResponseType = try decoder.decode(ResponseModel.self, from: data)
                let numberList = response.messageList.compactMap({ $0.keys })
                print("my numberList -> \(numberList)")
                completion(response)
    
            } catch let error {
                print(error)
                completion(nil)
            }
        }
    }
    

    USAGE:

    messageListAPI { response in
        /// If response is nil it's means error appear.
        /// Otherwise it is successful
        print(response)
    }
    

    You can use URLSession also

    guard let yourUrl = URL(string: "https://myUrl") else { return }
    URLSession.shared.dataTask(with: yourUrl) { (data, response , error) in      
        guard let data = data else { return }
        do {
        let decoder = JSONDecoder()
        let data = try decoder.decode(ResponseModel.self, from: data)
            print(data)
        } catch let error {
            print("Err", error)
        }
    }.resume()
    

    You can use these models for parse response JSON. And then you can get number list like that:

    let numberList = ResponseModel.messageList.compactMap({ $0.keys })
    

    If you have any question about use Codable models for API response please ask immediately.

    Enjoy.