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

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法