我在JSON Post中做错了什么? [英] What am I doing wrong in my JSON Post?

查看:105
本文介绍了我在JSON Post中做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to fill a model with data that comes from a Restful API. In my code I'm deserializing my JSON this way:

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的结果完全为空.我是否以错误的方式传递数据?

But I really don't know what I'm doing wrong because the result of my LoginModel is totally empty. Am I passing the data in a wrong way?

推荐答案

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

Your problem is that you are putting in the body of http request the params but in incorrect encoding.

尝试使用此代码

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客户端进行了测试,这是响应

Tested using a web http client this is the response

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

希望这会有所帮助

这篇关于我在JSON Post中做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆