首页 > 解决方案 > IOS swift将字典转换为json字符串会创建无效的JSON

问题描述

我有一个从 iOS api javascript 回调接收到的 json 对象,我会将相同的 json 发送到 php 后端以验证它。在android中一切正常,但在IOS应用程序中,问题是当我收到message.bodyjson时,它显示如下。

{
    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": &#8358,
        "order_currency_iso: NGN,
        "order_shipping" = 0;
        "order_stores":    {
            zOEZPU8sGCADHRbr8yw4 = {
                amount = 242550;
                currency = "&#8358;";
                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
    ]

标签: jsonswiftxcodedictionary

解决方案


由于类型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,请传递.prettyPrintedoptions:.


API在JSONDecoder这里不能很好地工作,因为您正在以字典的形式处理 JSON。JSONDecoder当你有Codable类型时效果最好。


推荐阅读