【问题标题】:issue while fetch data from nested json array从嵌套的json数组中获取数据时出现问题
【发布时间】:2019-11-18 15:49:40
【问题描述】:

我正在从 API 获取 JSON 数据,并且我已成功获得响应,但对我来说存在一些问题,即如何在没有密钥的情况下获得直接值,让我先向您展示我的响应

回复

{
  "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": ""
        }
      ]
    }
  ]
}

这是我的回复,现在我将向您展示我已成功获取 message_list 数组的数据,但问题是如何获取电话号码,这是您在我的回复中显示的主数组消息列表数组

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)
        }

    })
}

这是我成功获得message_list 的API 调用方法,谁能帮我获取号码​​列表

【问题讨论】:

    标签: ios json swift alamofire swifty-json


    【解决方案1】:

    您应该为响应创建这些模型:

    /// 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"
    }
    

    您可以将这些模型与 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)
            }
        }
    }
    

    用法:

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

    您也可以使用 URLSession

    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()
    

    您可以使用这些模型来解析响应JSON。然后你可以得到这样的号码列表:

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

    如果您对使用 Codable 模型进行 API 响应有任何疑问,请立即提问。

    享受吧。

    【讨论】:

    • 是的,我明白了,但是有了这个模型,我怎么能在 message_list 数组中获取数字列表
    • 您可以使用这一行 -> let numberList = ResponseModel.messageList.compactMap({ $0.keys }) ResponseModel 是您来自 API 的响应
    • 如何从 api 响应中追加数据到响应模型中请告诉我
    • 请检查我有更新 API 调用方法代码,我按照您在我的代码中显示的那样附加数据,但我收到错误 Cannot convert value of type 'JSON' to expected argument type '[[String : [MessageList]]]' 因为数据在 json 格式中
    • @VishalParmar 请打开另一个问题以填充到 tableViewCell
    【解决方案2】:

    只需粘贴您的 json 响应即可从 https://app.quicktype.io/ 获取您的模型

    URLSession.shared.dataTask(with: yourURL) { (data, resonse, err) in
                if err == nil{
    
                }else{
                    do{
                        let model = JSONDecoder().decode(YourModel.self, from: data!)
                    }catch(let decodeErr){
                        print(decodeErr)
                    }
                }
            }.resume()
    

    【讨论】:

      【解决方案3】:

      由于消息列表是一个数组,你可以尝试这样做-

      let data = json["message_list"]
      
      for (index, item) in data.enumerated() {
          print(item[index])
      }
      

      【讨论】:

      • Swift 中的 For 循环语法不同,也没有 console.log
      • 我的答案只是一个模型,您可以将其转换为您使用的任何语言。答案强调访问“数据”变量的可能方式
      • 是的,但是当我将其转换为 swift 时,我收到错误 Value of type 'JSON' has no member 'length'
      • 尊重所提出的问题,并以相同的编程语言编写代码。
      • 确保一件事,当您执行“var data = json['message_list']”时,您将获得什么数据?如果您正在获取对象,那么您将能够访问
      猜你喜欢
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多