jsonswiftweb-servicesrequestalamofire-request

Create a Json in Swift 5


I am new in swift and I want to make a post request with AlamoFire 5.4 and Swift 5

This is the object that I need to send to the server and I don't know how to create its equivalent in swift

[
  {
    "KEY": "LT_APP",
    "VALUE":"[{\"P_TIPO\":\"L\",\"P_PERNR\":\"925\",\"P_PASS\":\"GAMEROS01\",\"P_CEL\":\"6143194524\",\"P_TOKEN\":\"asdfgh\"}]"
  }
]

The content inside value is a string

In Postman looks like this

enter image description here

This is what I have

let jsonObject // Here is my problem xD how to build the object
AF.request(url,
           method: .post,parameters: jsonObject , encoding: JSONEncoding.default)
    .authenticate(username: user, password: password)
    .responseJSON { response in
        switch response.result {
            case .success(let json):
                let rtn = JSON(json)
                print(rtn["result"]["RESPONSE"][0])
            case .failure(let error):
                print(error)
        }
    }

I tried several ways to create it, inside a class, with a [String: Any] dictionary and finally the object declared directly

class Valores: NSObject{
var KEY:String
var VALUE:String

init(key: String, value: String){
    self.KEY = key
    self.VALUE = value
 }
}

var Arreglo = [Valores] = [Valores]()

let objeto : Valores = Valores(key: "LT_APP", value:"[{\"P_TIPO\":\"L\",\"P_PERNR\":\"925\",\"P_PASS\":\"GAMEROS01\",\"P_CEL\":\"6143194524\",\"P_TOKEN\":\"asdfgh\"}]")
Arreglo.append(Objeto)

Thanks


Solution

  • not sure its right way to do but may be this will work ..

        let arr = [["P_TIPO":"L"],["P_PERNR":"925"],["P_PASS":"GAMEROS01"],["P_CEL":"6143194524"],["P_TOKEN":"asdfgh"]]
        var text = "\(arr)"
        text = text.replacingOccurrences(of: "[", with: "", options: NSString.CompareOptions.literal, range:nil)
        text = text.replacingOccurrences(of: "]", with: "", options: NSString.CompareOptions.literal, range:nil)
        text = "[{\(text)}]"
        let rest = [["KEY": "LT_APP"], ["VALUE": "\(text)"]]
        print(rest)