2015-07-02 159 views
0

我有一個像斯威夫特解析JSON爲結構

struct Channel { 
    var id : Int = 0 
    var name = "" 
} 

一個結構,我得到的JSON從網址爲

{"channel_list":[{"channel_id":0,"channel_name」:」test1」},{「channel_id":0,"channel_name」:」test2」}]} 

但是我不能夠得到的數據作爲

func parseJson(anyObj:AnyObject) -> Array<Channel>{ 
    var list:Array<Channel> = [] 
    if anyObj is Array<AnyObject> { 
     var b:Channel = Channel() 
     for json in anyObj as! Array<AnyObject>{ 
      b.id = (json["channel_id"] as AnyObject? as? Int) ?? 0 
      b.name = (json["channel_name"] as AnyObject? as? String) ?? "" 
      list.append(b) 
     } 
    } 
    return list 
} 

//read code 
let anyObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0),error: nil) as AnyObject? 
     println(anyObj) 
     if let myobj=anyObj["channel_list"] as AnyObject { 
      self.Channellist=self.parseJson(anyObj!) 
     } 

這有什麼不對?

回答

0

首先,而是採用AnyObject,你應該投JSON響應的字典:[NSObject:AnyObject]然後安全投anyObj["channel_list"]到字典[[NSObject:AnyObject]] Array的結果,因爲這是你的JSON響應格式。

然後你需要在你的parseJSON函數中使用這個類型。我們也在簡化它,因爲不再需要做怪異的鑄件了。

此外,您傳遞錯誤的參數到您的函數(您使用anyObj而不是myObj)。

struct Channel { 
    var id : Int = 0 
    var name = "" 
} 

func parseJson(anyObj: [[NSObject:AnyObject]]) -> Array<Channel>{ 
    var list: Array<Channel> = [] 
    var b: Channel = Channel() 
    for json in anyObj { 
     b.id = (json["channel_id"] as? Int) ?? 0 
     b.name = (json["channel_name"] as? String) ?? "" 
     list.append(b) 
    } 
    return list 
} 

if let anyObj = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(0),error: nil) as? [NSObject:AnyObject] { 
    if let myobj = anyObj["channel_list"] as? [[NSObject:AnyObject]] { 
     self.Channellist=self.parseJson(myobj) 
    } 
} 

有改進的餘地:你可以爲你的結構創建一個初始化,例如,也創造了響應類型一typealias,使用map創建列表等

0

這裏是如何我會用Swift 2來做:

struct Channel { 
    var id : Int 
    var name: String 
    init?(JSON: [NSObject: AnyObject]?) { 
      guard let channelID = json["channel_id"] as? Int, let channelName = json["channel_name"] as? String 
      else { name = ""; id = 0; return nil } 
      name = channelName 
      id = channelID 
    } 
} 
func parseJSON(array: [[NSObject:AnyObject]]) -> [Channel?] { 
    return array.map { Channel(JSON: $0) } 
    // If you don't want to return optionals to channel you can do this instead: 
    // return array.map { Channel(JSON: $0) }.filter { $0 != nil }.map { $0! } 
} 
// And in the caller 
do { 
    guard let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [NSObject : AnyObject] 
    else { throw NSError(domain ... // Setup error saying JSON wasn't parsed. } 
    guard let arrayContents = dict["channel_list"] as? [[NSObject:AnyObject]] 
    else { throw NSError(domain ... // Setup error saying array wasn't found. } 
    let channels = parseJSON(arrayContents) 
} 
catch { 
    print(error) 
}