jsonswiftdictionaryalamofire

dictionary automatically adding backslash \ in swift


i try to put a json in a dictionary to send that dictionary to server using alamofire

i make json string but when i put it in a dictionary

dictionary automaticly add "\" to my jsonstring !

what should i do ?

here is my :



internal var registers : [  [String:String]  ] = []

registers.append(["fullName" :"ali","mid" :"406070","phoneNumber":"0912033"])

let jsonData = try! JSONEncoder().encode(registers)
let jsonString = String(data: jsonData, encoding: .utf8)!
let regjson = jsonString

let parameters: [String: String] = [
    "registers": regjson

   ]

and the result is

["registers": "[{\"mid\":\"406070\",\"fullName\":\"ali\",\"phoneNumber\":\"0912033\"}]"]

it should be like this

["registers": [{"fullName":"ali","mid":"406070","phoneNumber":"0912033"}]]


Solution

  • You're taking a dictionary, encoding it into a string of JSON. That process works fine. If you look at regjson, you'll see it's just fine. See for yourself:

    let registers = [
        ["fullName" :"ali","mid" :"406070","phoneNumber":"0912033"]
    ]
    
    let registersJsonData = try! JSONEncoder().encode(registers)
    let registersJsonString = String(data: registersJsonData, encoding: .utf8)!
    print(registersJsonString) // Looks just fine.
    // => [{"mid":"406070","fullName":"ali","phoneNumber":"0912033"}]
    

    But you're then taking this json string, and putting it another dictionary, and re-serializing the whole thing into yet another json string. The system doesn't know that the string value for the key "registers" is already a JSON-serialized string. It thinks it's a plain string no different than something like "Mary had a little lamb.". It serialized this string, like any other string. Doing so involves escaping out symbols that have other meanings in JSON's syntax.

    The system is behaving correctly, you're just asking it to do something that you don't want.

    What you're probably looking for is:

    let registers = [
        ["fullName": "ali", "mid" :"406070", "phoneNumber": "0912033"]
    ]
    
    let parameters = [
        "registers": registers
    ]
    
    
    let parametersJsonData = try! JSONEncoder().encode(parameters)
    let parametersJsonString = String(data: parametersJsonData, encoding: .utf8)!
    print(parametersJsonString)
    // => {"registers":[{"phoneNumber":"0912033","mid":"406070","fullName":"ali"}]}