2016-09-17 18:56

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

  • json
  • php
  • 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


  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!

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享