提问人:VjBegin 提问时间:8/29/2023 最后编辑:egleaseVjBegin 更新时间:8/30/2023 访问量:71
如何从 Json 中删除转义字符串?
How can I remove Escaped string from Json?
问:
我正在尝试向服务器发送请求。无法获取正确的格式 JSON 。请帮助解决此错误。 [ “{”ProductGroupId“:”994475“,”ProductId“:”994408“}”, “{”ProductGroupId“:”994475“,”ProductId“:”999737“}”, “{”ProductGroupId“:”994475“,”ProductId“:”999915“}”, “{”ProductGroupId“:”994475“,”ProductId“:”1194875“}” ]
self.productGroupList = json.response.result.packages[0].productGroups for index in 1..<self.productGroupList[3].products.count{
self.productGroupIdList.append(self.productGroupList[3].products[index].productGroupID) self.productGroupIdList.append(self.productGroupList[3].products[index].id) let dictionary = ["ProductGroupId": self.productGroupList[3].products[index].productGroupID, "ProductId": self.productGroupList[3].products[index].id] as [String : Any] do {
let jsonData:Data = try JSONSerialization.data( withJSONObject: dictionary, options: .fragmentsAllowed ) let jsonString = String(data: jsonData, encoding: .utf8)! self.Linelist.append(jsonString)
}
catch {
print(error.localizedDescription)
}
self.noOfCycleValuesDropDown()
}
}
}
catch{
print(error)
}
case .failure(let error): print("Error: \(error.localizedDescription)") // Handle the error if needed
}
}
}
我期待以下格式的请求
[
{
"ProductGroupId": "994475",
"ProductId": "994408"
},
{
"ProductGroupId": "994475",
"ProductId": "999737"
},
{
"ProductGroupId": "994475",
"ProductId": "999915"
},
{
"ProductGroupId": "994475",
"ProductId": "999951"
},
{
"ProductGroupId": "994475",
"ProductId": "1014043"
},
{
"ProductGroupId": "994475",
"ProductId": "1194891"
}
]
答:
1赞
Abdul Waheed
8/30/2023
#1
您可以使用 Encodables 非常轻松地获得所需的 JSON 数据 例如,创建一个产品结构
struct Product: Encodable {
let groupId: String
let productId: String
enum CodingKeys: String, CodingKey {
case groupId = "ProductGroupId"
case productId = "ProductId"
}
}
然后尝试按照您在循环中执行的方式添加值,但例如
var products: [Product] = []
products.append(Product(groupId: "994475", productId: "994408"))
products.append(Product(groupId: "994475", productId: "994408"))
products.append(Product(groupId: "994475", productId: "994408"))
products.append(Product(groupId: "994475", productId: "994408"))
要从 json 获取您需要的数据,请使用以下命令
/// This is what you need to send to server, use do try to get unwrapped object
let productsData: Data? = try? JSONEncoder().encode(products)
评论
dictionary
String(data: jsonData, encoding: .utf8)