ios - swift 从json中解析出一个值

标签 ios json swift

我正在尝试解析变量中的一个 int 值,但它返回 nil 或 0 我想要的值来自 customer_group_id。我正在使用快速。我已经从 json 文件中解析出其他信息,但在这个阶段它一直在搞砸。

  print("My Loyalty rank: " , newJson["loyalty_rank"][0]["customer_group_id"].string)
  myRank = newJson["loyalty_rank"][0]["customer_group_id"].intValue

这是json文件

{ "id":298,
  "name":"桃子 桜",
  "total_points_earned":164, 
  "points_available_to_spend":164,
  "loyalty_rank":{ 
       "customer_group_id":9,
       "name":"Baby Bee",
       "ratio":1
   },
  "order_history":[ 
  { }
  ],
 "barcode_id":"C-00000298"
 }

最佳答案

loyalty_rank[String:AnyObject] 意味着它的 Dictionary 不是数组 ...

尝试像这样打印

     // if its string
     print("My Loyalty rank: " , newJson["loyalty_rank"]["customer_group_id"].string)

     // if its Int
     print("My Loyalty rank: " , newJson["loyalty_rank"]["customer_group_id"].intValue)

最好使用 if letguard 之类的

    if let customerId = newJson["loyalty_rank"]["customer_group_id"].intValue{
        // customerId is int value
   }
   else{
       // not an int
   }

关于ios - swift 从json中解析出一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38519091/

相关文章:

ios - Voip 服务 (PKPush) 委托(delegate)方法未被调用

ios - 如何观察NSMutableArray中单个元素的变化?

ios - 核心数据获取请求与 NSFetchedResultsController 一对多关系

ajax - 如何在警报中显示 AJAX 响应消息?

快速更改当前 UITabBarController 的 ViewController

ios - swift 2 : Cannot subscript a value of type '[GKScore]?'

ios - 性能:点语法VS ivar

ios - 使用核心数据在 NSDate 属性中仅按年份过滤 TableView Controller

java - jackson : Partially update bean with json String

c# - 为什么我无法再反序列化这些数据?