2016-09-17 18:56
浏览 107

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


  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!

图片转代码服务由CSDN问答提供 功能建议

尝试使用PDO使用PHP / MySQL生成的JSON提要时,我遇到了一个有趣的问题。 默认情况下,查询的结果,例如 SELECT COUNT(id)FROM table name 作为 String 返回,但是当我对结果进行任何数学计算时,例如 $ result = $ result + 1; 结果是'正确的'数据类型。

在PHP中,这没问题,但是我使用JSON来 将这些结果发送到我的iOS应用程序,所以虽然我知道我想要在iOS中使用什么数据类型,但我不知道当它到达我时会是什么类型。 例如,我想这样做:

 如果让json = jsonResult为?  [String:Any] {
让score = jsonData [“score”]为?  Int ?? ??  0 
让years = jsonData [“years”]为? 字符串


  1. 如果得分是 JSON中的 String (例如得分:“7”),得分将最终为 0
  2. 如果 years 是JSON中的 Integer (例如 years:2015 ),则年份最终将为 nil

    我意识到使JSON正确是实现这一目标的最佳方式,但是在iOS中有可靠的方法吗? 为了这个问题,假设我不能改变JSON。

    我理想地寻找合理的单行,这将允许我转换为正确的数据类型,无论如何 它以前是什么类型的(即在上面的例子中 years 将成为 String ,无论它是 String 还是 JSON中的Int ,得分将成为 Int ,无论它是JSON中的 String 还是 Int


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanming7961 2016-09-17 19:01

    I think you can do somethink like

    let score = Int(jsonData["score"] as? String)
    打赏 评论

相关推荐 更多相似问题