首页 > 解决方案 > 尝试使用 Swift 将类型 [Any] 转换为 JSON 时出错

问题描述

我正在尝试将对象类型转换[Any]为 JSON 或我可以用来访问属性的东西。

脚步:

  1. 我从库中调用一个函数来连接到蓝牙设备并从它的内存中检索数据:
device.getMemoryData(totalCount: { (count) in
       print("There are \(count) elements in the memory")
    }, dataArray: { (data) in
      print("DATA --> \(data)")
      self.processReceivedData(data)
      // Here is where I receive the [Any] object 
    })

在步骤 1 中打印的接收到的对象符合以下内容:

[{
    side = 0;
    dataID = 07ebcd0070bf9a8116a8898e673e96e4;
    valueA = 69;
    valueC = 60;
    valueD = 0;
    irregular = 0;
    angleChange = 4;
    startAngle = 34;
    valueB = 106;
    time = "2015-01-01 13:33:00 +0000";
},
{
    side = 0;
    dataID = 0cf80347a86013689586d01d1d80fca5;
    valueA = 69;
    valueC = 60;
    valueD = 0;
    irregular = 0;
    angleChange = 2;
    startAngle = 37;
    valueB = 106;
    time = "2015-01-01 15:06:00 +0000";
}]
  1. 尝试访问对象包含的信息:

我尝试JSONSerialization

function processReceivedData(data:[Any]) {
  guard let processedData = try? JSONSerialization.data(withJSONObject: data, options: []) as? [[String: Any]] else {
      print("ERROR")
      return
    }
 print("JSON: \(processedData)")
// Run error when trying to serialize: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSTaggedDate)'
*** First throw call stack:
}

我也尝试使用以下方法对其进行迭代,for但出现编译错误:

function processReceivedData(data:[Any]) {
 for item in data {
      for (id, object) in item {
        print("ID: \(id), Object: \(object)")
      }
    }
}
// Compile error: Type 'Any' does not conform to protocol 'Sequence'

我需要访问数据以检查哪个位置具有最旧的时间戳并获取值。如何访问数据?

标签: iosarraysjsonswiftcasting

解决方案


正如评论的那样,你是data一个NSArrayNSDictionary您无需转换为 JSON 即可访问属性

尝试这个:

func processReceivedData(data:[Any]) {
    for item in data {
        if let item = item as? [String: Any] {
            for (id, object) in item {
                print("ID: \(id), Object: \(object)")
            }
        } else {
            print("Unexpected element: \(item)")
        }
    }
}

推荐阅读