我在JSON帖子中做错了什么?

时间:2017-07-10 19:07:42

标签: ios json swift post login

我必须使用来自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的结果是完全空的。我是以错误的方式传递数据吗?

1 个答案:

答案 0 :(得分:2)

你的问题是你在http请求的主体中加入params但编码不正确。

尝试使用此代码

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)

使用网络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   } }

希望这有帮助