【问题标题】:What am I doing wrong in my JSON Post?我在 JSON 帖子中做错了什么?
【发布时间】:2017-12-14 15:35:40
【问题描述】:

我必须用来自 Restful API 的数据填充模型。在我的代码中,我以这种方式反序列化我的 JSON:

func DoLogin(_ user:String, _ psw:String)
{
    let url = URL(string: "http://162.209.99.39:8080/MiClaroBackend/auth")
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url!)
    request.httpMethod = "POST"

    let paramToSend = "username=" + user + "&password=" + psw

    request.httpBody = paramToSend.data(using: String.Encoding.utf8)


    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (data, response, error) in

        guard let _:Data = data else
        {
            return
        }

        let json:AnyObject?

        do {
            json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
            if let parseJSON = json{

                let userInfo = parseJSON["userInfo"] as! NSDictionary
                self.loginModel.firstNames = userInfo["firstNames"] as! String
                self.loginModel.lastNames = userInfo["lastNames"] as! String
                self.loginModel.claroClubPoints = userInfo["claroClubPoints"] as! Int
                self.loginModel.imageProfileUrl = userInfo["imageProfileUrl"] as! String

                let mainProductService = parseJSON["mainProductService"] as! NSDictionary
                self.loginModel.idProductService = mainProductService["idProductService"] as! Int
                self.loginModel.lineType = mainProductService["lineType"] as! Int
                self.loginModel.lineName = mainProductService["lineName"] as! String
                self.loginModel.lineAlias = mainProductService["lineAlias"] as! String
                self.loginModel.profileType = mainProductService["profileType"] as! Int
                self.loginModel.idAccount = mainProductService["idAccount"] as! Int
                self.loginModel.idReceipt = mainProductService["idReceipt"] as! Int
                self.loginModel.category = mainProductService["category"] as! Int
                self.loginModel.clientType = mainProductService["clientType"] as! Int

                let userData = parseJSON["userData"] as! NSDictionary
                self.loginModel.userClientType = userData["clientType"] as! Int
                self.loginModel.docType = userData["docType"] as! Int
                self.loginModel.docNum = userData["docNum"] as! Int
                self.loginModel.email = userData["email"] as! String
                self.loginModel.msisdn = userData["msisdn"] as! Int

                let defaultServiceResponse = parseJSON["defaultServiceResponse"] as! NSDictionary
                self.loginModel.idTransaction = defaultServiceResponse["idTransaction"] as! String
                self.loginModel.message = defaultServiceResponse["message"] as! String
                self.loginModel.idResponse = defaultServiceResponse["idResponse"] as! Int

            }
        } catch {
            let error = ErrorModel()
            error.phrase = "PARSER_ERROR"
            error.code = -1
            error.desc = "Parser error in login action"
        }
    })

    task.resume()
}

但我真的不知道我做错了什么,因为我的 LoginModel 的结果完全是空的。我是否以错误的方式传递数据?

【问题讨论】:

  • 放置断点并检查代码流。
  • 你知道你是不是在获取数据但是JSON解析错误?或者您根本没有获取数据?
  • 我没有得到数据!

标签: ios json swift post login


【解决方案1】:

您的问题是您将参数放入 http 请求的正文中,但编码不正确。

尝试使用此代码

let paramToSend = ["username":user,"password":psw]
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters)

而不是

let paramToSend = "username=" + user + "&password=" + psw
request.httpBody = paramToSend.data(using: String.Encoding.utf8)

使用 web http 客户端测试这是响应

{   "accessToken": "t9iqu0pe8is3vmt2t7b1k90rpv",   "userInfo": {
    "firstNames": "Consumer",
    "lastNames": "BeMobile",
    "claroClubPoints": 914,
    "imageProfileUrl": "http://162.209.99.39:8080/MiClaroBackend/myprofile/image/show/imageProfile.png"   },   "mainProductService": {
    "idProductService": "51993112847",
    "lineType": 1,
    "name": "993 112 847",
    "alias": "TUN 20",
    "profileType": 1,
    "idAccount": "961851",
    "idReceipt": "961852",
    "category": 1,
    "clientType": 1   },   "userData": {
    "clientType": 1,
    "docType": "002",
    "docNum": "41313343",
    "email": "consumer.client@bemobile.com.mx",
    "msisdn": "995 456 679"   },   "defaultServiceResponse": {
    "idTransaction": "2KHHVIC4SC00",
    "idResponse": 0,
    "message": "OK",
    "messageType": 0   } }

希望对你有帮助

【讨论】:

  • 非常感谢你,你太棒了,这真的帮助了我! :D
  • 欢迎您@ZitaNoriegaEstrada 我很高兴能帮到您!,最好的问候
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2021-06-28
  • 1970-01-01
  • 2011-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多