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
414 views
in Technique[技术] by (71.8m points)

ios - Unable to extract data properly from JSON in swift

I have a this kind of json object in my response after parsing json string to object

[
    "requestId": 1, 
    "response": {
        code = SUCCESS;
    }, 
    "messageId": ACTION_COMPLETE
]

I am trying to extract requestId using

responseMsg["requestId"] as! Int

I am getting this error

Could not cast value of type 'NSTaggedPointerString' (0x21877a910) to 'NSNumber' (0x218788588).

I tried it changing to Int(responseMsg["requestId"] as! String)! This thing is working for positive numbers but not for negative numbers probably bcz when requestId = -2 it throws me an error

Could not cast value of type '__NSCFNumber' (0x21877a000) to 'NSString' (0x218788290).

I tried with different other solution too but did not work.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

For parsing the JSON data, its better use Codable instead of manually parsing everything.

For JSON format,

{
    "requestId": 1,
    "response": {
        "code":"SUCCESS"
    },
    "messageId": "ACTION_COMPLETE"
}

Create Models like,

struct Root: Decodable {
    let requestId: String?
    let messageId: String
    let response: Response

    enum CodingKeys: String, CodingKey {
        case requestId, messageId, response
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        if let id = try? values.decode(Int.self, forKey: .requestId) {
            requestId = String(id)
        } else if let id = try? values.decode(String.self, forKey: .requestId) {
            requestId = id
        } else {
            requestId = nil
        }
        messageId = try values.decode(String.self, forKey: .messageId)
        response = try values.decode(Response.self, forKey: .response)
    }
}

Now, parse the JSON data using,

do {
    let root = try JSONDecoder().decode(Root.self, from: data)
    print(root.requestId) //access requestId like this....
} catch {
    print(error)
}

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

...