需要对具有json对象的数组进行排序

时间:2018-01-03 20:18:11

标签: json swift

json数据从dataTask网络调用返回并在此处分配给数组:

   let json = try? JSONSerialization.jsonObject(with: data!, options: [])
      if let jsonarray = json as? [Any] {
        self.cardArray = jsonarray
     }

json看起来像这样:

[ 
  {
    "deviceID":114,
    "UserName":"freds@hotmail.com",
    "Name":"under sink",
    "UniqueId":"D0:B5:C2:F2:B8:88",
    "RowCreatedDateTime":"2018-01-02T16:07:31.607"
  }
]

如何根据名为RowCreatedDateTime的json属性对此数组进行排序(降序)?

我尝试了这个,但它不起作用:

cardArray.sort{
    $0.RowCreatedDateTime < $1.RowCreatedDateTime
}

2 个答案:

答案 0 :(得分:2)

假设所有字典都包含密钥RowCreatedDateTime,您必须按键获取值。你不能在字典上使用点符号。

cardArray.sort{
    ($0["RowCreatedDateTime"] as! String) < $1["RowCreatedDateTime"] as! String
}

如果您知道数组的类型为[[String:Any]],则永远不会将其转换为更加未指定的[Any]

cardArray声明为词典数组

var cardArray = [[String:Any]]()

以这种方式解析JSON

do {
    if let jsonArray = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
        self.cardArray = jsonArray
    }
} catch { print(error) }

考虑在Swift 4中使用Codable将JSON解析为结构体。这使事情变得更容易。

答案 1 :(得分:0)

使cardArray [[String:Any]]代替[Any]

var cardArray = [[String:Any]]()

然后

let json = try? JSONSerialization.jsonObject(with: data!, options: [])
if let jsonarray = json as? [[String:Any]] {
    self.cardArray = jsonarray
} else {
    self.cardArray = []
}

最后

self.cardArray.sort {
    guard let left = $0["RowCreatedDateTime"] as? String else { return true }
    guard let right = $1["RowCreatedDateTime"] as? String else { return false }

    return left < right
}