本文介绍了Swift-解析数据错误-Swift.DecodingError.dataCorrupted的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将SwiftSoup与Codable结合使用以获取正确的元素并解析数据.但是,我收到此错误:

I'm using SwiftSoup in combination with Codable to get the correct element(s) and parse the data. However, I receive this error:

JSON decode failed: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.})))

我已经在线查看了,确保我的数据正确匹配,甚至将预期的类型从Int更改为String,但出现错误,指出了预期的Int.

I've looked online, ensure my data matches correctly, even change the expected types from Int to String but got an error stating an Int was expected.

这是我正在接收的数据,可以在控制台中打印:

This is the data I am receiving and can print in the console:

data -
{"test":0,"ppace":85,"pshooting":92,"ppassing":91,"pdribbling":95,"pdefending":38,"pphysical":65,"acceleration":91,"sprintspeed":80,"agility":91,"balance":95,"reactions":94,"ballcontrol":96,"dribbling":96,"positioning":93,"finishing":95,"shotpower":86,"longshotsaccuracy":94,"volleys":88,"penalties":75,"interceptions":40,"headingaccuracy":70,"marking":32,"standingtackle":35,"slidingtackle":24,"vision":95,"crossing":85,"freekickaccuracy":94,"shortpassing":91,"longpassing":91,"curve":93,"jumping":68,"stamina":72,"strength":69,"aggression":44,"composure":96}

这是我的功能:

 func parseData() {
    do {
    let html = try String(contentsOf: url!, encoding: String.Encoding.ascii)
        let doc: Document = try! SwiftSoup.parse(html)
        let elements = try doc.getAllElements()
        for element in elements {
            switch element.id() {
            case "player_stats_json":

                let content = try! element.getElementsContainingText("ppace").text()
                print(content.utf8)
                let jsonData = content.data(using: .utf8)
                    do {
                        self.player = try JSONDecoder().decode(PlayerModel.self, from: Data(jsonData!))
                    } catch let jsonError as NSError {
                        print("JSON decode failed: \(jsonError)")
                        print("data - \(content)")
                    }
            default:
                break
            }
        }

    } catch Exception.Error(type: let type, Message: let message) {
        print(type)
        print(message)
    } catch {
        print("")
    }
    }

这是我的模型文件:

struct PlayerModel: Codable {
    var test: Int
    var ppace: Int
    var pshooting: Int
    var ppassing: Int
    var pdribbling: Int
    var pdefending: Int
    var pphysical: Int
    var acceleration: Int
    var sprintspeed: Int
    var agility: Int
    var balance: Int
    var reactions: Int
    var ballcontrol: Int
    var dribbling: Int
    var positioning: Int
    var finishing: Int
    var shotpower: Int
    var longshotsaccuracy: Int
    var volleys: Int
    var penalties: Int
    var interceptions: Int
    var headingaccuracy: Int
    var marking: Int
    var standingtackle: Int
    var slidingtackle: Int
    var vision: Int
    var crossing: Int
    var freekickaccuracy: Int
    var shortpassing: Int
    var longpassing: Int
    var curve: Int
    var jumping: Int
    var stamina: Int
    var strength: Int
    var aggression: Int
    var composure: Int
}

我已经将变量名与每个键匹配了两倍和三倍.我已经将输出的数据粘贴到了在线JSON验证器中的控制台中,并且没有出现错误.我现在是genuinley,因为我不知道自己哪里出了问题,现在才挠头.

I've double and tripled checked the variable names match up with each key. I've pasted the outputted data in the console in an Online JSON validator, and no errors appear. I'm genuinley left scratching my head right now, because I can't understand where I've gone wrong.

推荐答案

我仍然不知道您的解析有什么问题.我已经设法解析了您的html,但我不知道为什么当尝试使用Int而不是Uint8时,它总是无法返回正确的值.这对我有用:

I still have no idea whats wrong with your parsing. I've managed to parse your html but I have no idea why when trying to use Int instead of Uint8 it kept failing to return the right values. This is what worked for me:

import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
struct PlayerModel: Codable {
    let test: UInt8
    let ppace: UInt8
    let pshooting: UInt8
    let ppassing: UInt8
    let pdribbling: UInt8
    let pdefending: UInt8
    let pphysical: UInt8
    let acceleration: UInt8
    let sprintspeed: UInt8
    let agility: UInt8
    let balance: UInt8
    let reactions: UInt8
    let ballcontrol: UInt8
    let dribbling: UInt8
    let positioning: UInt8
    let finishing: UInt8
    let shotpower: UInt8
    let longshotsaccuracy: UInt8
    let volleys: UInt8
    let penalties: UInt8
    let interceptions: UInt8
    let headingaccuracy: UInt8
    let marking: UInt8
    let standingtackle: UInt8
    let slidingtackle: UInt8
    let vision: UInt8
    let crossing: UInt8
    let freekickaccuracy: UInt8
    let shortpassing: UInt8
    let longpassing: UInt8
    let curve: UInt8
    let jumping: UInt8
    let stamina: UInt8
    let strength: UInt8
    let aggression: UInt8
    let composure: UInt8
}


let url = URL(string:"https://www.futbin.com/21/player/541/lionel-messi")!
URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data, let html = String(data: data, encoding: .utf8) else { return }
    if let start = html.range(of: #"<div style="display: none;" id="player_stats_json">"#)?.upperBound,
       let end = html[start...].range(of: #"</div>"#)?.lowerBound {
        let json = html[start..<end]
        do {
            let player = try JSONDecoder().decode(PlayerModel.self, from: Data(json.utf8))
            print(player)
        } catch {
            print(error)
        }
    }
}.resume()


这将打印


This will print

这篇关于Swift-解析数据错误-Swift.DecodingError.dataCorrupted的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:57