来自Tracker Network API(SWIFT)的JSON

时间:2018-10-31 03:17:34

标签: ios json swift xcode api

我无法从API读取数据。我可以在Xcode中查看我的API中的所有数据。

这是我要解析的数据。

  "data": {
    "id": "2f464c52-81a5-4b2d-9d08-21baf10134bd",
    "type": "player",
    "metadata": {
      "statsCategoryOrder": [
        "levels",
        "combat",
        "game",
        "bullets",
        "ekia-enemy-killed-in-action",
        "objective",
        "team-play",
        "extra"
      ],
      "platformId": 1,
      "platformUserHandle": "BarMexico67",
      "accountId": "2f464c52-81a5-4b2d-9d08-21baf10134bd",
      "cacheExpireDate": "10/31/2018 1:45:55 AM"
    },
    "stats": [
      {
        "metadata": {
          "key": "level",
          "name": "Level",
          "categoryKey": "levels",
          "categoryName": "Levels",
          "isReversed": false,
          "iconUrl": "https://cod-cdn.tracker.gg/assets/ranks/rank_6.png"
        },
        "value": 6.0,
        "percentile": 92.0,
        "displayValue": "6"
      },
      {
        "metadata": {
          "key": "KDRatio",
          "name": "KD Ratio",
          "categoryKey": "combat",
          "categoryName": "Combat",
          "isReversed": false
        },
        "value": 0.39,
        "percentile": 96.0,
        "displayValue": "0.39",
        "displayRank": ""
      },

我正在尝试获取“水平”和“ KD比率”的值,并放置在标签上。

但是,我收到一条错误消息“ keyNotFound(CodingKeys(stringValue:” stats“,intValue:nil)

这是我当前的代码。任何帮助都会很棒。

struct Data: Decodable {
    let id: String?
    let type: String?
    let stats: [Stats]
}

struct Stats: Decodable {
    let name: String?
    let categoryName: String?
    let displayValue: Int?
    let value: Int?
}

class StatTrackerVC: UIViewController {

    @IBOutlet weak var accountNameLabel: UILabel!

    let blackOps4TrackerNetworkAPI = "4db06ff7-4499-494d-8d75-93a9b38292a3"
    let urlString = URL(string: "https://cod-api.tracker.gg/v1/standard/bo4/profile/1/BarMexico67")


    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonUrlString = "https://cod-api.tracker.gg/v1/standard/bo4/profile/1/BarMexico67"
        guard let url = URL(string: jsonUrlString) else
            { return }

        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.addValue(blackOps4TrackerNetworkAPI, forHTTPHeaderField: "TRN-Api-Key")


        URLSession.shared.dataTask(with: request) { (data, response, err) in
            //Perhaps Check Err
            //Check Response Status 200 OK

            guard let data = data else { return }

//            let dataAsString = String(data: data, encoding: .utf8)
//            print(dataAsString!)

            do {
                let stats = try JSONDecoder().decode(Data.self, from: data)
                print(stats)

            } catch let jsonErr {
                print("Error Serializing JSON:", jsonErr)
            }
        }.resume()

    }

1 个答案:

答案 0 :(得分:1)

实际上stats对象不在data对象内部,而是位于同一级别。因此,stats数组不应位于Data类型内。同样在stat对象内部,metaData是子对象,其键像keycategoryKeycategoryName等,而valuepercentile和{{ 1}}是displayValue对象的一部分。可解码类型的正确实现如下,

stat

因此,现在您应该struct TrackerResponse: Decodable { let data: StatData? let stats: [Stat]? } struct StatData: Decodable { let id: String? let type: String? let accountId: String? let platformId: Int? } struct Stat: Decodable { let value: Int? let metadata: StatMeta? let percentile: Int? let displayValue: String? } struct StatMeta: Decodable { let key: String? let name: String? let categoryKey: String? let categoryName: String? } decode,如下所示,

TrackerResponse