json - IOS swift将字典转换为json字符串会创建无效的JSON
问题描述
我有一个从 iOS api javascript 回调接收到的 json 对象,我会将相同的 json 发送到 php 后端以验证它。在android中一切正常,但在IOS应用程序中,问题是当我收到message.body
json时,它显示如下。
{
OrderNumber = 01869756;
"customer_key" = SLApO64gAktgmuLl;
"order_address" = "{\"address\":\"No. 7 Ogwui Road Enugu\",\"city\":\"Enugu\"}";
"order_amount" = 242550;
"order_currency" = "₦";
"order_currency_iso" = NGN;
"order_shipping" = 0;
"order_stores" = {
zOEZPU8sGCADHRbr8yw4 = {
amount = 242550;
currency = "₦";
delivery = 0;
total = 242550;
};
};
"order_subtotal" = 242550;
"order_subtotal_cent" = 24255000;
"order_tax" = "4123.35";
"order_tax_cent" = 412335;
"order_total" = "246673.35";
"order_total_cent" = 24667335;
status = 200;
}
当我将上述 IOS 格式传递给 php 后端json_decode($payload)
时,它总是返回 null。请问如何将其转换为我在下面的代码中尝试过的真正的 json 格式,但它不起作用?
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode("\(message.body)") {
if let jsonString = String(data: jsonData, encoding: .utf8) {
print("dictFromJSON", jsonString)
}
}
我也试过这个
if let response = message.body as? Dictionary<String, AnyObject> {
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode("\(response)") {
if let jsonString = String(data: jsonData, encoding: .utf8) {
print("dictFromJSON", jsonString)
}
}
}
但是上面的代码输出类似于下面的东西,它不是一个有效的 json。
[
"OrderNumber": 01869756,
"customer_key": SLApO64gAktgmuLl,
"order_address": {\"address\":\"No. 7 Ogwui Road Enugu\",\"city\": \"Enugu\"};
"order_amount": 242550,
"order_currency": ₦,
"order_currency_iso: NGN,
"order_shipping" = 0;
"order_stores": {
zOEZPU8sGCADHRbr8yw4 = {
amount = 242550;
currency = "₦";
delivery = 0;
total = 242550;
};
};
"order_subtotal": 242550,
"order_subtotal_cent: 24255000,
"order_tax": 4123.35,
"order_tax_cent": 412335,
"order_total": 246673.35",
"order_total_cent": 24667335,
"status" = 200
]
解决方案
由于类型message.body
是__NSFrozenDictionaryM
,您可以使用以下方法将其转换为 JSON 字符串JSONSerialization
:
if let jsonData = try? JSONSerialization.data(withJSONObject: message.body, options: []) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
print("dictFromJSON", jsonString)
}
}
如果您想查看格式精美的 JSON,请传递.prettyPrinted
给options:
.
API在JSONDecoder
这里不能很好地工作,因为您正在以字典的形式处理 JSON。JSONDecoder
当你有Codable
类型时效果最好。
推荐阅读
- angular - 在 Angular 8 中,如何通过拖动抽屉的边缘来调整 mat-drawer 的大小?
- ruby-on-rails - 为 Rails 表单输入分配唯一 ID 的最佳实践是什么?
- java - charAt() 之后的双反转(“”)
- javascript - 我需要正则表达式的银行路由号码在 javascript 中以 01 到 12 或 21 到 32 开头
- javascript - nodejs 响应 HTML 文件,其中包含带有 src 属性的脚本标记
- elasticsearch - 如何将 Ui Path orchestrator 与 Kibana 链接
- angular - 如何在打字稿中创建具有未知数量属性的接口?
- flutter - 扑动中GoogleMapController的含义是什么?
- javascript - Firebase 和 Express,每次更改 firebase 的值时,我的 api 都会发送重复响应
- jenkins - 使用 BeanStalk、GitHub、CodePipeline 和 Jenkins 为 CI/CD 优化子网配置