在Swift中使用可编码解析JSON

D.查尔兹

我正在尝试在Swift中解析带有可编码的JSON。我之前已经成功完成此操作,但是我有一个带有一些数组的更复杂的JSON对象,遇到了麻烦。

这是我的JSON:

{
"data": [ {
    "type":"player",
    "id":"account.7e5b92e6612440349afcc06b7c390114",
    "attributes": {
        "createdAt":"2018-04-06T04:59:40Z",
        "name":"bob",
        "patchVersion":"",
        "shardId":"pc-na",
        "stats":null,
        "titleId":"bluehole-pubg",
        "updatedAt":"2018-04-06T04:59:40Z"
    },
    "relationships": {
        "assets": {
            "data":[]
        },
        "matches": {
            "data": [
            {"type":"match","id":"3e2a197a-1453-4569-b35b-99e337dfabc5"},
            {"type":"match","id":"15f41d2f-9da2-4b95-95ca-b85e297e14b7"},
            {"type":"match","id":"a42c496c-ad92-4d3e-af1f-8eaa2e200c2b"}
            {"type":"match","id":"b6e33df5-4754-49da-9a0f-144842bfc306"},
            {"type":"match","id":"5b357cd1-35fe-4859-a2d7-48f263120bbd"},
            {"type":"match","id":"99fc5f81-c24c-4c82-ae03-cd21c94469c0"},
            {"type":"match","id":"1851c88e-6fed-48e8-be84-769f20f5ee6f"},
            {"type":"match","id":"e16db7ea-520f-4db0-b45d-649264ac019c"},
            {"type":"match","id":"6e61a7e7-dcf5-4df5-aa88-89eca8d12507"},
            {"type":"match","id":"dcbf8863-9f7c-4fc9-b87d-93fe86babbc6"},
            {"type":"match","id":"0ba20fbb-1eaf-4186-bad5-5e8382558564"},
            {"type":"match","id":"8b104f3b-66d5-4d0a-9992-fe053ab4a6ca"},
            {"type":"match","id":"79822ea7-f204-47f8-ae6a-7efaac7e9c90"},
            {"type":"match","id":"1389913c-a742-434a-80c5-1373e115e3b6"}
            ]
        }
    },
    "links": {
        "schema":"",
        "self":"https://api.playbattlegrounds.com/shards/pc-na/players/account.7e5b92e6612440349afcc06b7c390114"
    }
}],
"links": {
    "self":"https://api.playbattlegrounds.com/shards/pc-na/players?filter[playerNames]=dchilds64"
    },
"meta":{}
}

这是我正在使用的模型:

public struct PlayerResponse: Codable {
    let data: [Player]
}

对于玩家:

public struct Player: Codable {
    let type: String
    let id: String
    let attributes: Attributes
    let relationships: Relationships
}

对于属性:

public struct Attributes: Codable {
    let name: String
    let patchVersion: String
    let shardId: String
    let titleId: String
    let updatedAt: String
}

对于关系:

public struct Relationships: Codable {
    let matches: Matches
}

对于比赛:

public struct Matches: Codable {
    let data: [Match]
}

匹配:

public struct Match: Codable {
    let type: String
    let id: String

}

解码为:

let players = try decoder.decode([Player].self, from: jsonData)

我有运行我的网络请求的此功能:

    func getPlayerData(for name: String, completion: ((Result<[Player]>) -> Void)?) {
    var urlComponents = URLComponents()
    urlComponents.scheme = "https"
    urlComponents.host = "api.playbattlegrounds.com"
    urlComponents.path = "/shards/\(regionShard.rawValue)/players"
    let playerNameItem = URLQueryItem(name: "filter[playerNames]", value: "\(name)")
    urlComponents.queryItems = [playerNameItem]
    guard let url = urlComponents.url else { fatalError("Could not create URL from components") }
    print(url)

    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    request.setValue("bearer \(apiKey)", forHTTPHeaderField: "Authorization")
    request.setValue("application/vnd.api+json", forHTTPHeaderField: "Accept")

    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)
    let task = session.dataTask(with: request) { (responseData, response, responseError) in
        DispatchQueue.main.async {
            if let error = responseError {
                completion?(.failure(error))
            } else if let jsonData = responseData {
                let decoder = JSONDecoder()

                do {
                    let players = try decoder.decode([Player].self, from: jsonData)
                    completion?(.success(players))
                } catch {
                    completion?(.failure(error))
                }
            } else {
                let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Data was not retrieved from request"]) as Error
                completion?(.failure(error))
            }
        }
    }

    task.resume()
}

我面临的问题是,当我尝试运行网络请求时出现此错误:

我认为我的可编码结构有问题,但我不确定。有人可以指出正确的方向来寻找我的错误吗?

四个

我建议您从头开始,因为JSONDecoder结构越复杂(与任何编译器一样)的错误就越严重。让我们看看我们能走多远:

您的Match结构很不错:

public struct Match: Codable {
    let type: String
    let id: String

}

let decoder = JSONDecoder()
let mData = """
   {"type":"match","id":"3e2a197a-1453-4569-b35b-99e337dfabc5"}
   """.data(using:.utf8)!
let match = try! decoder.decode(Match.self, from:mData)

print(match)

这里没有意外的问题。简而言之,Matches您已经遇到了第一个错误,而不是意外的错误

public struct Matches: Codable {
    let data: [Match]
}

let mtchsData = """
    {
        "data": [
            {"type":"match","id":"3e2a197a-1453-4569-b35b-99e337dfabc5"},
            {"type":"match","id":"15f41d2f-9da2-4b95-95ca-b85e297e14b7"},
            {"type":"match","id":"a42c496c-ad92-4d3e-af1f-8eaa2e200c2b"}
            {"type":"match","id":"b6e33df5-4754-49da-9a0f-144842bfc306"},
            {"type":"match","id":"5b357cd1-35fe-4859-a2d7-48f263120bbd"}
        ]
    }
    """.data(using:.utf8)!
do {
    let mtches = try decoder.decode(Matches.self, from:mtchsData)
    print(mtches)
} catch {
    print(error)
}

将显示以下错误:

"dataCorrupted(Swift.DecodingError.Context(codingPath: [],
debugDescription: "The given data was not valid JSON.", 
underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840
    "Badly formed array around character 233."
UserInfo={NSDebugDescription=Badly 
    formed array around character 233.})))\n"

这是一个小错误,您在的第3行上缺少逗号data Array加上所有这些都会很好,但是如果您的服务中出现这种情况,则必须先对其进行修复。

我想您已经知道了,并且知道了逐步构建结构的方法。在顶层,你会发现你的顶层结构超出了数组Player,它实际上是一个Dictionary"data"作为其唯一的键,可以在正确建模PlayerResponse为@AnkitJayaswal已经指出。这已经产生了两个错误,这些是我很容易发现的错误,但是正如我在继续构建测试之前所建议的那样,您将知道“较低”级别可以正确解析并且可以专注于该问题。手。

以上所有内容都可以在Playground中轻松实现,并且不需要在此过程中实际调用WebService。当然,您将必须这样做import Cocoa,但是您已经知道这一点。无论如何,它始终可以通过将问题分解为较小的部分来降低复杂性。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章