2017-07-30 55 views
0

我想从以下JSON提取第一“字段1”“字段2”值来取出第一个重复元素嵌套的JSON:如何使用SWIFT 3

{ 
"channel": { 
    "id": 297681, 
    "name": "Basement", 
    "description": "Climate Node Upstairs", 
    "latitude": "0.0", 
    "longitude": "0.0", 
    "field1": "Temperature", 
    "field2": "Humidity", 
    "created_at": "2017-07-04T21:43:23Z", 
    "updated_at": "2017-07-30T16:52:48Z", 
    "last_entry_id": 17803 
}, 
"feeds": [ 
    { 
     "created_at": "2017-07-30T16:50:46Z", 
     "entry_id": 17802, 
     "field1": "68.18", 
     "field2": "53.80" 
    }, 
    { 
     "created_at": "2017-07-30T16:52:48Z", 
     "entry_id": 17803, 
     "field1": "68.18", 
     "field2": "53.90" 
    } 
] 
} 

我有以下工作代码打印两种进料的文字:当我尝试提取第一馈送进入

let url = URL(string: "https://api.thingspeak.com/channels/297681/feeds.json?api_key=xxxx&results=2")! 

    let task = URLSession.shared.dataTask(with: url) 
    { 
     (data, response, error) 
     in 
     if let data = data, let rawJSON = try? JSONSerialization.jsonObject(with: data, options:.allowFragments) as? [String: Any] 
     { 
      print ("rawjason set") 

      if let json = rawJSON as? [String: Any] 
      { 
       //print(json) //should print json 
       // print("<-------->`") 
       // print(json["channel"]) 
       let channel = json["channel"] as! [String: Any] 
       // print(channel["name"]!) 

       //let locname = channel["name"]! as! [String: String] 
       let locname = channel["name"]! 
       print("<-- name next -->") 
       print(locname) 


       let feeds = json["feeds"] 
       print("<feeds>") 
       print(feeds) 
然而

,我尝试不活像ķ。

我已经试过:

//fails with Type Any> has no subscript members: 
let feed1 = feeds[0] 

道歉,如果此之前已被覆盖,我看着堆栈溢出几个类似的问题,但不能使其适应我的情况。

+0

因为'feed'的类型是'Any'。将其转换为数组:let feeds = json [“feeds”] as! [[String:AnyObject]]' –

+0

[type any?没有下标成员](https://stackoverflow.com/questions/38956785/type-any-has-no-subscript-members) – vadian

回答

0

由于json类型为Any,因此需要将其转换为更具体的类型,即字典数组。

if let feeds = json["feeds"] as? [[String:Any]] { 
    for feed in feeds { 
     if let field1 = feed["field1"] as? Double { 
      //do whatever you need to with field1 
     } 
     if let field2 = feed["field2"] as? Double { 
      //do whatever you need to with field2 
     } 
    } 
}