FAParser, 在用户默认值中,JSON解析+ 归档&取消归档

分享于 

10分钟阅读

GitHub

  繁體 雙語
JSON Parsing + Archiving & Unarchiving in User Defaults
  • 源代码名称:FAParser
  • 源代码网址:http://www.github.com/fahidattique55/FAParser
  • FAParser源代码文档
  • FAParser源代码下载
  • Git URL:
    git://www.github.com/fahidattique55/FAParser.git
    Git Clone代码到本地:
    git clone http://www.github.com/fahidattique55/FAParser
    Subversion代码到本地:
    $ svn co --depth empty http://www.github.com/fahidattique55/FAParser
    Checked out revision 1.
    $ cd repo
    $ svn up trunk
    
    FAParser

    Alt text

    Swift versionSupport Dependecy ManagerVersionLicensePlatform

    特性

    • 你可以使用苹果编码技术的key-value 来解析 JSON,使用最少的代码行。
    • 你可以使用最少的代码行将&取消存档自定义对象。
    • 你可以将模型转换为JSON请求格式 比如 [ 字符串: Any]字典
    • 你可以进一步将这里字典转换为JSON字符串格式

    安装

    CocoaPods

    CocoaPods 是 Cocoa 项目的依赖项管理器。 你可以使用以下命令安装它:

    $ gem install cocoapods

    要使用CocoaPods将FAParser集成到你的Xcode项目中,请在你的Podfile 中指定它:

    source 'https://github.com/CocoaPods/Specs.git'platform :ios, '10.0'use_frameworks!
    target '<Your Target Name>'dopod 'FAParser'end

    然后,运行以下命令:

    $ pod install

    预先要求

    • key-value 编码
    • 要了解 key-value-coding,请访问苹果 KVC 文档

    用法

    JSON解析

    • 假设下面是API调用的JSON响应对象
    // Let say we get a JSON object of Movie as response from API call,{ 
     "id":"m_123456789",
     "Title":"Batman",
     "Year":"1989",
     "Rated":"PG-13",
     "Released":"23 Jun 1989",
     "Runtime":"126 min",
     "Genre":"Action, Adventure",
     "Director":"Tim Burton",
     "Writer":"Bob Kane (Batman characters), Sam Hamm (story), Sam Hamm (screenplay), Warren Skaaren (screenplay)",
     "Actors":"Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl",
     "Language":"English, French",
     "Country":"USA, UK",
     "Awards":"Won 1 Oscar. Another 9 wins & 22 nominations.",
     "Poster":"https://images-na.ssl-images-amazon.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg",
     "Ratings":[ 
     { 
     "Source":"Internet Movie Database",
     "Value":"7.6/10" },
     { 
     "Source":"Rotten Tomatoes",
     "Value":"72%" },
     { 
     "Source":"Metacritic",
     "Value":"69/100" }
     ],
     "Author":{ 
     "name":"Fahid Attique",
     "email":"fahidattique55@gmail.com" },
     "Metascore":"69",
     "imdbRating":"7.6",
     "imdbVotes":"279,110",
     "imdbID":"tt0096895",
     "Type":"movie",
     "DVD":"25 Mar 1997",
     "BoxOffice":"N/A",
     "Production":"Warner Bros. Pictures",
     "Website":"N/A",
    }

    带 key-value 代码的解析

    importFAParserlet movie = Movie.objectfrom(json: responseFromAPI)

    类电影

    • 确保JSON响应 MATCHES 键的NAME 与模态类的属性/键的NAME 完全相同,因为苹果在KVC中遵循它。
    • 对于"id"之类的特殊情况,你可以使用"movie_id"或者"movieid"等其他名称
    classMovie: NSObject {
     // MARK: Properties// Array of Nested JSON objectvar Ratings:Array<Rating>?=nil// Nested JSON objectvar Author:Author?=nil// JSON simple keysvar movie_id :String=""// Special casevar Title :String=""var Year:String=""var Rated:String=""var Released:String=""var Runtime:String=""var Genre:String=""var Director:String=""var Writer:String=""var Actors:String=""var Language:String=""var Country:String=""var Awards:String=""var Poster:String=""var Metascore:String=""var imdbRating:String=""var imdbVotes:String=""var imdbID:String=""var Type:String=""var DVD:String=""var BoxOffice:String=""var Production:String=""var Website:String=""// MARK: initializationoverrideinit() {
     super.init()
     }
     // MARK: KVC + JSON ParsingoverridefuncsetValue(_value: Any?, forKeykey: String) {
     iflet aVlaue = value {
     if key =="Author" { // As our JSON have nested JSON object with this key // Parse Nested JSON using FAParser  Author = Author.objectfrom(json: value) 
     }
     elseif key =="Ratings" { // As out JSON have an array of nested JSON objects// Parse Array of Nested JSON objects using FAParser  Ratings = Rating.objectsfrom(jsonArray: value as!Array)
     }
     else{ // In case of simple JSON keys i.e: Not a nested JSON object or an Array of JSON objectsif key =="id"{ // Special cases only. Otherwise no need of adding if statement movie_id = value
     }
     else{
     // Following code will automatically parse remaining fields of your JSON to model as their names are same as our Model propertiessuper.setValue(aVlaue, forKey: key)
     }
     }
     }
     }
     overridefuncsetValue(_value: Any?, forUndefinedKeykey: String) {
     // In case there is a key in JSON that does not exist as a property in our Model Classprint("This class is not key-value-compliant for key: (key) & value : (value)")
     }
    }

    类作者

    classAuthor: NSObject {
     // MARK: Propertiesvar name:String=""var email:String=""// MARK: initializationoverrideinit() {
     super.init()
     }
     // MARK: KVC + JSON ParsingoverridefuncsetValue(_value: Any?, forKeykey: String) {
     // Following code will automatically parse JSON to model as their names are same as our Model propertiessuper.setValue(value, forKey: key) 
     }
     overridefuncsetValue(_value: Any?, forUndefinedKeykey: String) {
     // In case there is a key in JSON that does not exist as a property in our Model Classprint("This class is not key-value-compliant for key: (key) & value : (value)")
     }
    }

    等级等级

    classRating: NSObject {
     // MARK: Propertiesvar Source:String=""varValue:String=""// MARK: initializationoverrideinit() {
     super.init()
     }
     // MARK: KVC + JSON ParsingoverridefuncsetValue(_value: Any?, forKeykey: String) {
     // Following code will automatically parse JSON to model as their names are same as our Model propertiessuper.setValue(value, forKey: key) 
     }
     overridefuncsetValue(_value: Any?, forUndefinedKeykey: String) {
     // In case there is a key in JSON that does not exist as a property in our Model Classprint("This class is not key-value-compliant for key: (key) & value : (value)")
     }
    }

    归档&存档

    • 假设你想要将电影类对象归档到UserDefaults中。 只从 Class faautocode继承它"
    importFAParser// Subclass your Custom Modal Class with FAAutoCode Class classMovie: FAAutoCode { 
     ...// Additional code, if exist  
     // MARK: NSCodingrequiredinit(coderaDecoder: NSCoder) {
     super.init(coder: aDecoder)
     }
    }
    • 所有完成FAAutoCode类将自动为类电影编写NSCoding协议代码 !
    // Now you can Archive your custom object with fillowing lines of codelet data = NSKeyedArchiver.archivedData(withRootObject:<custom object>)
    UserDefaults.standard.set(data, forKey: "<Any Key you want>")
    UserDefaults.standard.synchronize()// To Unarchive your custom object from User Defaults, use the following codeiflet data = UserDefaults.standard.value(forKey: "<Any Key you want>") {
     movie = NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as!<Custom Class>?}

    AFJSONable

    • 假设你想将电影类对象转换为字典,以便在某些api请求中传递它。 仅符合协议"azjsonable""
    importFAParser// conform your Modal Class with AZJSONable Protocol classMovie: AZJSONable { 
     var title:String=""var actor:String=""}
    • 要转换我们只需要做这个
    let movie: Movie =Movie()
     movie.title="La La Land" movie.actor="Emma Stone"let dictFormat :[String:Any] = (movie.toDictionary()) // will convert full object to dictionary// To convert it in JSON String  dictFormat.jsonString() // or use  dictFormat.jsonString(prettify: true)

    许可证

    FAParser在MIT许可证下可用。 有关详细信息,请参阅许可证文件。

    作者

    Fahid Attique - ( https://github.com/fahidattique55 )


    PAR  USE  用户  DEF  arc  默认  
    相关文章