Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

ios - Convert quoted number from JSON (swift)

I have a struct like bellow:

struct MyStruct: Codable {
    
    var id: Int?

}

and the JSON that i was receiving from server was like this:

{
    "id": 12345
}

But now server-side decided to send all numbers as quoted numbers like this:

{
    "id": "12345"
}

When decoding this json using JSONDecoder().decode i got an error,

The data couldn’t be read because it isn’t in the correct format

Is there any way, (except writing custom Encodable and Decodable implementation for every struct that i created up to now) to solve this problem? For example doing something on JSONDecoder()

question from:https://stackoverflow.com/questions/65860328/convert-quoted-number-from-json-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it by implementing Decodable protocol's required initializer, init(from:):

extension MyStruct {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        let idString = try values.decode(String.self, forKey: .id)
        id = Int(idString)
    }
}

And don't forget to decode values of other properties.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...