2016-11-07 77 views
0

SwiftyJSON是一個非常有用的Swift插件,可以通過各種方法導入(CocoaPods,Carthage等),我在許多項目中使用它,因爲它們通常需要JSON文件。所以我想要一個很好的簡單函數,我可以用必要的參數調用,並從我的JSON文件中獲取我的原始String值。簡單的getJSON()函數

回答

0

這裏是我創造的功能,隨時給自己(做當然都需要SwiftJSON到Xcode斯威夫特項目內正確地整合)使用它...

func getJSON(value: [String], fileName: String) -> String{ 
    guard let path = Bundle.main.path(forResource: fileName, ofType: "json"), 
     let jsonData = NSData(contentsOfFile: path) else{ 
      print("Couldn't find the file on disk or failed to read it") 
      return "ERR." 
    } 

    let jsonObject = JSON(data: jsonData as Data) 

    guard let jsonValue = jsonObject[value].string else{ 
     print("FAILED to find JSON object") 
     return "ERR." 
    } 

    return jsonValue 

} 

這個功能的使用示例會是let myJsonValue = getJSON(value: ["people","person1"], fileName: "database")這將得到值person1組在JSON文件中名爲database.json。所以,如果database.json文件看起來是這樣的

{ 
    "people" : { 
     "person1" : "Bob", 
     "person2" : "Steve", 
     "person3" : "Alan", 
    } 
} 

該函數將返回"Bob"

希望的值,這是任何人的幫助,或者如果你有這方面的任何建議,那麼請讓我知道!總是有建設性的批評。

1

步驟1.我們將創建在它一個構造方法和模型類一個協議

protocol JSONable { 
    init?(parameter: JSON) 
} 

class Style: JSONable { 
    let ID    :String! 
    let name   :String! 

    required init(parameter: JSON) { 
     ID   = parameter["id"].stringValue 
     name   = parameter["name"].stringValue 
    } 

    /* JSON response format 
    { 
     "status": true, 
     "message": "", 
     "data": [ 
     { 
      "id": 1, 
      "name": "Style 1" 
     }, 
     { 
      "id": 2, 
      "name": "Style 2" 
     }, 
     { 
      "id": 3, 
      "name": "Style 3" 
     } 
     ] 
    } 
    */ 
} 

步驟2.我們將創建JSON的擴展,這將轉換JSON來建模類型對象

extension JSON { 
    func to<T>(type: T?) -> Any? { 
     if let baseObj = type as? JSONable.Type { 
      if self.type == .array { 
       var arrObject: [Any] = [] 
       for obj in self.arrayValue { 
        let object = baseObj.init(parameter: obj) 
        arrObject.append(object!) 
       } 
       return arrObject 
      } else { 
       let object = baseObj.init(parameter: self) 
       return object! 
      } 
     } 
     return nil 
    } 
} 

第3步。使用Alamofire或其他代碼的代碼。

Alamofire.request(.GET, url).validate().responseJSON { response in 
     switch response.result { 
      case .success(let value): 
       let json = JSON(value) 

       var styles: [Style] = [] 
       if let styleArr = json["data"].to(type: Style.self) { 
        styles = styleArr as! [Style] 
       } 
       print("styles: \(styles)") 
      case .failure(let error): 
       print(error) 
     } 
} 

我希望這會有用。

請參閱此鏈接瞭解更多信息。
https://github.com/SwiftyJSON/SwiftyJSON/issues/714