【问题标题】:Xcode - Parse string into usable data structureXcode - 将字符串解析为可用的数据结构
【发布时间】:2020-11-01 12:56:52
【问题描述】:

我有一个字符串(下面的 sn-p),我知道它是 parsing it here 的有效 json。我想要实现的最终解析是based off this PHP code。当我尝试以下代码时,我似乎无法让 xcode 保持快乐,因为我似乎继续制作 <Any> 的数组,要么得到错误 Value of type 'Any' has no subscripts 要么解包 nil

任何想法如何解析这个将不胜感激。

if let jsonArray = try JSONSerialization.jsonObject(with: jsonString.data(using: .utf8)!,options : .allowFragments) as? Array<Any> {
                let a = jsonArray[0] as? Array<Any>
                let a = jsonArray[0] as? Array<Any>
                let b =  a?[1] as? Array<Any>
                let c = b?[1] as? Array<Array<Any>>

}

片段 - full string here

[["comic books",[["","","","","","","","","Ba6eX5HWBc3btAa6mJ_4Cg","0ahUKEwjR7NSWsOHsAhXNLc0KHTrMB68QmBkIAigA",["comic books",0]
]
,["","","","","","","","","Ba6eX5HWBc3btAa6mJ_4Cg","0ahUKEwjR7NSWsOHsAhXNLc0KHTrMB68QmBkIBCgB","","","","",["Ba6eX5HWBc3btAa6mJ_4Cg","0ahUKEwjR7NSWsOHsAhXNLc0KHTrMB68Q8BcIBSgAMAA",["330 Army Trail Rd","Glendale Heights, IL 60139"]
,"",["","","",["https://www.google.com/search?q\u003dGot+Comics+Inc,+330+Army+Trail+Rd,+Glendale+Heights,+IL+60139\u0026ludocid\u003d7330282631276370350#lrd\u003d0x880fac8c25bbd32b:0x65ba6537347199ae,1","105 

【问题讨论】:

  • 那是糟糕的 JSON 格式。
  • 哦,是的……

标签: json swift parsing


【解决方案1】:

首先,让我们声明数据类型:

struct Item {
    let name: String?
    let location: String?
    let phone: String?
}

使用SwiftyJSON,你可以很好地将PHP代码转换成这样的:

var items = [Item]()
if let json = try? JSON(data: jsonData), let arr = json[0][1].array {
    for itemArray in arr {
        guard let itemDetails = itemArray[14].array else { continue }
        let name = itemDetails[11].string
        let location = itemDetails[18].string
        let phone = itemDetails[178][0][0].string
        items.append(Item(name: name, location: location, phone: phone))
    }
}

为了好玩,下面是上述代码的更短、更实用、更易读的实现:

let items = (try? JSON(data: jsonData))?[0][1].array?
    .compactMap { $0[14].array }
    .map { Item(name: $0[11].string, location: $0[18].string, phone: $0[178][0][0].string) }
    ?? []

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 2011-04-19
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多