如何在数组中快速解析数组中的json 4

时间:2018-08-02 14:32:53

标签: json swift

我无法从此API响应访问StatusList数组。我将如何获得这些信息?

我当前的代码是行不通的。

let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]

for list in (parsedData["StatusList"] as? [String])!{
    for shipmentstatus in list["Details"]{
                        //doesn't work
                    }
                }

这是JSON

{
   "MobileAPIError":"",
   "StatusList":{
      "ErrorMessage":"",
      "Details":[
     {
        "Pro":"000000000",
        "BlNumber":"000000",
        "ReferenceNumber":"",
        "Scac":"CNWY",
        "Carrier":"XPO LOGISTICS FREIGHT, INC.",
        "ShipperCode":"xx999",
        "ShipperName":"W B EQUIPMENT",
        "ShipperCity":"WOOD RIDGE",
        "ShipperState":"NJ"
     },
     {
        "Pro":"0000000",
        "BlNumber":"#00000-R",
        "ReferenceNumber":"",
        "Scac":"CNWY",
        "Carrier":"XPO LOGISTICS FREIGHT, INC.",
        "ShipperCode":"xx999",
        "ShipperName":"W B EQUIPMENT",
        "ShipperCity":"WOOD RIDGE",
        "ShipperState":"NJ"
     },
     ]
   }
}

编辑:我想尝试使用JSONDecoder,因为它看起来像是一个不错的解决方案。

这项工作可以吗?

struct ShipmentStatusList: Decodable {
    let MobileAPIError: String
    let StatusList: StatusListItems

    enum CodingKeys : String, CodingKey {
        case MobileAPIError
        case StatusList
    }
}
struct StatusListItems{
    let ErrorMessage: String
    let Details: [Details]
}

struct Details {
    let Pro: String
    let BLNumber: String
    let ReferenceNumber: String
}

1 个答案:

答案 0 :(得分:1)

StatusList的值是一个字典,请注意{},数组是Details中键statusList的值

if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
   let statusList = parsedData["StatusList"] as? [String:Any],
   let details = statusList["Details"] as? [[String:Any]] {
       for detail in details {
          print(detail["Pro"])
       }
   }
}

千万不要做(... as? ...)!之类的事情!

相应的Codable结构是

struct Status: Codable {
    let mobileAPIError: String
    let statusList: StatusList

    enum CodingKeys: String, CodingKey { case mobileAPIError = "MobileAPIError", statusList = "StatusList" }
}

struct StatusList: Codable {
    let errorMessage: String
    let details: [Detail]

    enum CodingKeys: String, CodingKey { case errorMessage = "ErrorMessage", details = "Details" }
}

struct Detail: Codable {
    let pro, blNumber, referenceNumber, scac: String
    let carrier, shipperCode, shipperName, shipperCity: String
    let shipperState: String

    enum CodingKeys: String, CodingKey {
        case pro = "Pro", blNumber = "BlNumber", referenceNumber = "ReferenceNumber"
        case scac = "Scac", carrier = "Carrier", shipperCode = "ShipperCode"
        case shipperName = "ShipperName", shipperCity = "ShipperCity", shipperState = "ShipperState"
    }
}

do {
     let result = try JSONDecoder().decode(Status.self, from: data!)
     print(result)
} catch { print(error) }