【问题标题】:How to convert array of integer inside string to array of string?如何将字符串内的整数数组转换为字符串数组?
【发布时间】:2019-04-18 11:28:44
【问题描述】:

我有一个[String : Any] 的字典,其中一个值是Int 类型的数组。它看起来像这样:

 "file_name" : "anImage.png"
 "type" : "2"
 "data_bytes" : "[-119,80,78,71,13,10,26,10,0,13,73,72,68,82,0,0,2,0,2,0,8,6,-12,120,-4]"

现在我试图将键 data_bytes 的值作为整数数组,但编译器说我不能将 String 转换为 Array 或其他东西。我尝试了以下代码:

dictionary["data_bytes"] as? [Int]      //Failed
dictionary["data_bytes"] as? [NSNumber] //Failed
dictionary["data_bytes"] as? Array    //Failed
dictionary["data_bytes"] as? [Int8]     //Failed
dictionary["data_bytes"] as? String     //Success

我也尝试循环遍历字符串中的所有字符:

 (dictionary["data_bytes"] as? String).flatMap( Int($0) ?? 0 ) //Failed

但它给出了例外,因为在循环时,有像 [ ] , 这样的字符是不可转换的。

我应该如何将其转换为整数数组?

【问题讨论】:

  • 简单的 JSON 规则:用双引号括起来的所有内容都是String,一个字符串。 凡事,也不例外。
  • @TheNeil 这不是重复的。仔细看看。
  • 谢谢。旗帜被收回。

标签: ios arrays swift dictionary


【解决方案1】:

这是一个json字符串

if let str =  dictionary["data_bytes"] as? String {

     do { 
         let res = try JSONDecoder().decode([Int].self,from:Data(str.utf8))
         print(res)
     }
     catch {
         print(error)
     } 

}

【讨论】:

  • 太棒了。这行得通。我不知道怎么做。但确实如此。
  • @Jamil 如果答案有助于他人识别正确答案,请标记为已接受。
  • @Jamil,该字符串是有效的 JSON 数字数组,因此可以使用 JSONDecoder 轻松解析它
猜你喜欢
  • 2015-07-04
  • 2021-12-13
  • 1970-01-01
  • 2012-02-26
  • 2017-11-27
  • 2021-08-26
  • 2019-04-21
相关资源
最近更新 更多