可以通过struct解析从json到int的float

时间:2018-03-26 21:21:59

标签: json swift parsing

我需要用游戏指令解析一个json,但在后端他们将之前在Int中的param更改为Float(IDK为什么,但现在就是这样)

这是错误

  

意外错误:dataCorrupted(Swift.DecodingError.Context(codingPath:,debugDescription [ios_apps.HomeResponse(在_B9BDF2CE76592A42518B3A0888B1E0F5 CodingKeys)。游戏,ios_apps.Game(在_BAE470AF8C81659CF18E4A8D481877B9 CodingKeys).counterLeft。]:"解析的JSON数字< 53422.434>不适合Int。",underlyingError:nil))。

这是结构

import Foundation


struct Game : Decodable {
    let gameId : String?
    let currentTime : String?
    let counterLeft : Int?
    let counterStart : String?
    let counterStep : String?
    let gameEnd : String?
    let gameIntroduction : String?
    let gamePlay : Bool?
    let gameStart : String?
    let gameType : String?
    let gameUserPlayed : Bool?
    let picture : String?
    let started : Bool?

   // private var counterLeft : Float?


}

struct CounterLeft: Codable, Loopable {
    let counterLeft : Int?
    enum CodingKeys: String, CodingKey {

        case counterLeft = "counterLeft"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        counterLeft = try Int(values.decode(Float.self, forKey: .counterLeft))
    }
}

响应形式json

game =     {
    counterLeft = "53422.434";
    counterStart = "2018-03-26T07:00:00.000Z";
    counterStep = countDown;
    currentTime = "2018-03-26T21:09:37.562Z";
    gameEnd = "2018-03-28T15:00:51.000Z";
    gameId = 5ab906957889034b223b3ba4;
    gameIntroduction = "Lorem Ipsum";
    gamePlay = 0;
    gameStart = "2018-03-27T12:00:00.000Z";
    gameType = spinwheel;
    gameUserPlayed = 0;
    picture = "/files/1522075335538L.png";
    started = 1;
};

我需要counterLeft在Int中用于倒计时的原因

1 个答案:

答案 0 :(得分:1)

使用 Double 。我运行一个简单的测试数据模型,它正在运行。 这是swift 4中的代码:

const string a_string = "a long string with \" .. with \" again ... ... ";