class Matchess {
var matchBack : MatchBack?
var matchTeam1 : MatchTeam1?
var matchTeam2 : MatchTeam2?
var matchLeague :MatchLeague?
var matchRound :MatchRound?
var matchTime :MatchTime?
var matchDay: MatchDay?
var matchStatus :MatchStatus?
var matchCountDown :MatchCountDown?
var matchIconTeam1 : MatchIconTeam1?
var matchIconTeam2 : MatchIconTeam2?
var matchCountDownDateTime :MatchCountDownDateTime?
var matchId : MatchId?
var matchImage : MatchImage?
var matchScore :MatchScore?
var nextMapId :NextMapId?
var matchTimePlayed : MatchTimePlayed?
var matchPenalty :MatchPenalty?
init(json:[String:Any])
{
matchBack = MatchBack.init(json: json["match_back"] as! Dictionary<String,Any>)
matchTeam1 = MatchTeam1.init(json: json["match_teamI"]as! Dictionary<String,Any>)
matchTeam2 = MatchTeam2.init(json: json["match_teamII"]as! Dictionary<String,Any>)
matchLeague = MatchLeague.init(json: json["match_league"]as!Dictionary<String,Any>)
matchRound = MatchRound.init(json: json["match_round"]as! Dictionary<String,Any>)
matchTime = MatchTime.init(json: json["match_time"]as! Dictionary<String,Any>)
matchDay = MatchDay.init(json: json["match_day"]as! Dictionary<String,Any>)
matchStatus = MatchStatus.init(json: json["match_status"]as! Dictionary<String,Any>)
matchCountDown = MatchCountDown.init(json: json["match_count_down"]as! Dictionary<String,Any>)
matchIconTeam1 = MatchIconTeam1.init(json: json["match_icon_teamI"]as! Dictionary<String,Any>)
matchIconTeam2 = MatchIconTeam2.init(json: json["match_icon_teamII"]as! Dictionary<String,Any>)
matchCountDownDateTime = MatchCountDownDateTime.init(json: json["match_count_down_date_time"]as! Dictionary<String,Any>)
matchId = MatchId.init(json: json["Value"]as! Dictionary<String,Any>)
matchImage = MatchImage.init(json: json["match_image"]as! Dictionary<String,Any>)
matchScore = MatchScore.init(json: json["match_score"]as! Dictionary<String,Any>)
nextMapId = NextMapId.init(json: json["next_map_id"]as! Dictionary<String,Any>)
matchTimePlayed = MatchTimePlayed.init(json: json["match_time_played"]as! Dictionary<String,Any>)
matchPenalty = MatchPenalty.init(json: json["match_penalty"]as! Dictionary<String,Any>)
}
init(json:AnyObject)
{
matchBack = MatchBack.init(json: json["match_back"] as! Dictionary<String,Any>)
matchTeam1 = MatchTeam1.init(json: json["match_teamI"]as! Dictionary<String,Any>)
matchTeam2 = MatchTeam2.init(json: json["match_teamII"]as! Dictionary<String,Any>)
matchLeague = MatchLeague.init(json: json["match_league"]as!Dictionary<String,Any>)
matchRound = MatchRound.init(json: json["match_round"]as! Dictionary<String,Any>)
matchTime = MatchTime.init(json: json["match_time"]as! Dictionary<String,Any>)
matchDay = MatchDay.init(json: json["match_day"]as! Dictionary<String,Any>)
matchStatus = MatchStatus.init(json: json["match_status"]as! Dictionary<String,Any>)
matchCountDown = MatchCountDown.init(json: json["match_count_down"]as! Dictionary<String,Any>)
matchIconTeam1 = MatchIconTeam1.init(json: json["match_icon_teamI"]as! Dictionary<String,Any>)
matchIconTeam2 = MatchIconTeam2.init(json: json["match_icon_teamII"]as! Dictionary<String,Any>)
matchCountDownDateTime = MatchCountDownDateTime.init(json: json["match_count_down_date_time"]as! Dictionary<String,Any>)
matchId = MatchId.init(json: json["Value"]as! Dictionary<String,Any>)
matchImage = MatchImage.init(json: json["match_image"]as! Dictionary<String,Any>)
matchScore = MatchScore.init(json: json["match_score"]as! Dictionary<String,Any>)
nextMapId = NextMapId.init(json: json["next_map_id"]as! Dictionary<String,Any>)
matchTimePlayed = MatchTimePlayed.init(json: json["match_time_played"]as! Dictionary<String,Any>)
matchPenalty = MatchPenalty.init(json: json["match_penalty"]as! Dictionary<String,Any>)
}
}
Это массив объектов, получаемых с сервера, каждый объект имеет класс, например:фатальная ошибка: неожиданно нашли ноль в то время как разворачивание необязательное значение в то время как получил сын массив объектов
class MatchTeam1 {
var teamId : String?
var text : String?
var mapId : String?
var textColor: String?
var extId : String?
init(json:AnyObject)
{
teamId = json["Id"] as? String
text = json["Text"] as? String
mapId = json["MapId"] as? String
textColor = json["TextColor"] as? String
extId = json["ExtId"] as? String
}
init(json:[String:Any])
{
teamId = json["Id"] as? String
text = json["Text"] as? String
mapId = json["MapId"] as? String
textColor = json["TextColor"] as? String
extId = json["ExtId"] as? String
}
}
В главном контроллере представления я получаю весь файл с сыном, даже я могу получить область, но при попытке получить доступ к объектам массива приложение сбой и выдача ошибки выше: код главного контроллера:
if let urlt : NSURL = NSURL(string:url)!
{
print(urlt)
}
let request = NSMutableURLRequest(URL: NSURL(string:url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = parameters.dataUsingEncoding(NSUTF8StringEncoding)
//request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameter, options: .PrettyPrinted)
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else
{
print("no data found: \(error)")
return
}
do
{
print(data)
var jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error
//thrown, but not NSDictionary
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? NSMutableDictionary
{
print(son) // getting all son file data
let test = json["Matches"]
print(test)// prints the array of son objects
let test2 = Matchess.init(json: test!)//getting error here
//let test2 = Matchess.init(json: json["Matches"]! as! Dictionary<String,Any>)// getting error
test2. // can access all objects in array test , but cannot print them, since crashing.
print(test2)// crashing
}
else
{
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
// print("Error could not parse JSON: \(jsonStr)")
}
}
catch let parseError as NSError
{
print(parseError.description)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
Я сделал 2 inits в классе только потому, что первый не работал, поэтому я попытался изменить формулу второго, но также не работал. Любая справка
Ответ зависит от структуры полученного JSON. В принципе любой '!' Может вызвать ошибку. Установите контрольную точку исключения и отлаживайте код. – vadian
init (json: AnyObject) .... в этом init, я получаю ошибку: фатальная ошибка: неожиданно найден nil при развертывании необязательного значения –
Возможный дубликат [Что делает «фатальная ошибка: неожиданно найденный nil при распаковке Необязательное значение «означает?» (Http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Moritz