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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch