dongtang6681 2016-09-17 18:56
浏览 110
已采纳

Swift:JSON属性转换 - 将JSON数据类型改变为相同的Swift数据类型

I've come across an interesting issue when trying to use a JSON feed generated by PHP/MySQL using PDO. By default, the result of a query e.g. SELECT COUNT(id) FROM table name is returned as a String, but when I do any mathematical calculations on the result e.g. $result = $result + 1; the result is the 'correct' datatype.

In PHP, that's been no problem, but I'm using JSON to send these results to my iOS app, so although I know what datatype I want something to be in iOS, I don't know what type it's going to be when it reaches me. For example, I'd like to do:

if let json = jsonResult as? [String:Any] {
    let score = jsonData["score"] as? Int ?? 0
    let years = jsonData["years"] as? String
}

But:

  1. If score is a String in the JSON (e.g. score:"7"), score will just end up as 0
  2. If years is an Integer in the JSON (e.g. years:2015), years will end up as nil

I realise that making the JSON correct is the best way to achieve this, however is there a reliable way to do this in iOS? For the sake of this question, assume that I cannot change the JSON.

I'm ideally looking for a sensible one-liner, that will allow me to convert to the correct datatype, regardless of what type it was previously (i.e. in the above example years will become a String, regardless of whether it was a String or Int in the JSON, and score will become an Int regardless of whether it was a String or an Int in the JSON)?

Many thanks in advance!

  • 写回答

1条回答 默认 最新

  • duanming7961 2016-09-17 19:01
    关注

    I think you can do somethink like

    let score = Int(jsonData["score"] as? String)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下:
  • ¥15 Mac(标签-IDE|关键词-File) idea
  • ¥15 潜在扩散模型的Unet特征提取
  • ¥15 iscsi服务无法访问,如何解决?
  • ¥15 感应式传感器制作的感应式讯响器