字典会迅速添加反斜杠\

问题描述 投票:-2回答:2

我尝试在字典中放入json以使用alamofire将字典发送到服务器

我制作json字符串,但是当我将其放入字典中时

字典自动将“ \”添加到我的jsonstring中!

我该怎么办?

这是我的:



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

   ]

结果为

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

应该是这样

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

json swift dictionary alamofire
2个回答
1
投票

我该怎么办?

没什么,反斜杠是虚拟的。它们被添加以在文字字符串中显示双引号。


0
投票

[您正在使用字典,将其编码为JSON字符串。该过程运行良好。如果您查看regjson,您会发现它很好。自己看看:

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

但是您要使用此json字符串,然后将其置为另一个字典,然后将整个内容重新序列化为另一个json字符串。唯一可行的方法是转义字符串的特殊字符。该系统运行正常,您只是在要求它执行您不想要的操作。

您可能正在寻找的是:

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"}]}
© www.soinside.com 2019 - 2024. All rights reserved.