IzzyParser iOS

IzzyParser 是一个用于序列化和反序列化 JSON API 对象的库。

Test codecov Platform Pod version SPM Top language License

安装

Swift Package Manager

  1. 使用 Xcode 11 或更高版本,前往 File > Swift Packages > Add Package Dependency
  2. 粘贴项目 URL: https://github.com/undabot/izzyparser-ios.git
  3. 点击 “Next”,选择项目目标,然后点击 “Finish”
  4. 导入 IzzyParser

CocoaPods

CocoaPods 是 Cocoa 项目的依赖管理器。要使用 CocoaPods 将 IzzyParser 集成到你的 Xcode 项目中,请在你的 Podfile 中指定它

target '<Your Target Name>' do
    pod 'IzzyParser'
end

然后,运行以下命令

$ pod install

用法

定义资源

所有资源必须继承 Resource 类。

基本资源

class Author: Resource {
    
    override class var type: String {
        return "people"
    }
    
    required init(id: String) {
        super.init(id: id)
    }
}

使用 customKeys 进行序列化,以及 typesForKeys 进行反序列化的资源

class Article: Resource {
    @objc var title: String = ""
    @objc var author: Author?
    @objc var comment: Comment?
    
    override class var type: String {
        return "articles"
    }
    
    // Custom coding keys
    override public class var customKeys: [String: String] {
        return ["komentar": "comment"]
    }
    
    override public class var typesForKeys: [String: CustomObject.Type] {
        return ["komentar": Comment.self]
    }
    
    init(id: String, title: String, author: Author, comment: Comment? = nil) {
        self.title = title
        self.author = author
        self.comment = comment
        super.init(id: id)
    }
    
    required init(id: String) {
        super.init(id: id)
    }
}

带有自定义反序列化器的对象

class Comment: NSObject, CustomObject {
    @objc var id: String
    @objc var content: String
    required init(objectJson: [String: Any]) {
        self.id = objectJson["id"] as? String ?? ""
        self.content = objectJson["content"] as? String ?? ""
    }
}

Codable 自定义对象

class CodableComment: NSObject, CodableCustomObject {
    var id: String?
    var content: String?
}

注册资源

所有资源必须注册到 Izzy 实例。

// Creating resource map
let resourceMap: [Resource.Type] = [
    Article.self,
    Author.self
]

// Registering resources
let izzy = Izzy()
izzy.registerResources(resources: resourceMap)

开发者经常忘记将资源注册到资源映射中。如果资源未注册,反序列化器将为缺失的对象返回 nil(这是预期的行为)。但是,你可以在开发时启用调试模式,这样如果资源未注册,Izzy 将抛出一个错误。不要为生产代码启用调试模式,因为它会导致崩溃,它应该仅用于调试目的 - 以便你可以检测到哪些资源未注册。

// Registering resources
let izzy = Izzy()
izzy.isDebugModeOn = true
izzy.registerResources(resources: resourceMap)

序列化

序列化单个资源

// Article serialization
let author = Author(id: "authorID")
let article = Article(id: "articleID", title: "Article title", author: author)

let serializedArticle = izzy.serialize(resource: article)

输出

// Serialized article JSON:
/**
	{
	  "data" : {
	    "attributes" : {
	      "title" : "Article title"
	    },
	    "id" : "articleID",
	    "type" : "articles",
	    "relationships" : {
	      "author" : {
	        "data" : {
	          "id" : "authorID",
	          "type" : "people"
	        }
	      }
	    }
	  }
	}
*/

使用自定义属性序列化来序列化单个资源

// Article serialization with custom author serialization
let customRelationshipDict: [String: Any] = [
    "name": "John",
    "surname": "Smith",
    "age": NSNull()
]

serializedArticle = izzy.serializeCustom(resource: article, relationshipKey: "author", relationshipValue: customRelationshipDict)

输出

// Serialized article JSON:
/**
	{
	  "data" : {
	    "attributes" : {
	      "title" : "Article title"
	    },
	    "id" : "articleID",
	    "type" : "articles",
	    "relationships" : {
	      "author" : {
	        "name" : "John",
	        "surname" : "Smith",
	        "age" : null
	      }
	    }
	  }
	}
*/

序列化资源集合

let author = Author(id: "authorID")
let article = Article(id: "articleID", title: "Article title", author: author)

let serializedResourceCollection = izzy.serialize(resourceCollection: [article, article])

输出

// Serialized resource collection:
 /**
 	{
	  "data" : [
	    {
	      "attributes" : {
	        "title" : "Article title"
	      },
	      "id" : "articleID",
	      "type" : "articles",
	      "relationships" : {
	        "author" : {
	          "data" : {
	            "id" : "authorID",
	            "type" : "people"
	          }
	        }
	      }
	    },
	    {
	      "attributes" : {
	        "title" : "Article title"
	      },
	      "id" : "articleID",
	      "type" : "articles",
	      "relationships" : {
	        "author" : {
	          "data" : {
	            "id" : "authorID",
	            "type" : "people"
	          }
	        }
	      }
	    }
	  ]
	}
 */

反序列化

反序列化单个资源

输入 JSON

// JSON data:
/**
	{
    "data": {
        "type": "articles",
        "id": "1",
        "attributes": {
            "title": "Rails is Omakase",
            "komentar": {
                "id": "11",
                "content": "Custom content"
            }

        },
        "relationships": {
            "author": {
                "links": {
                    "self": "/articles/1/relationships/author",
                    "related": "/articles/1/author"
                },
                "data": { "type": "people", "id": "9" }
            }
        }
    }
}
*/
// Article deserialization
do {
    let document: Document<Article> = try izzy.deserializeResource(from: data)
    let article = document.data
    
    let id = article?.id
} catch let error {
    print(error.localizedDescription)
}

反序列化资源集合

// Article deserialization
do {
    let document: Document<[Article]> = try izzy.deserializeCollection(data)
    let articles = document.data
} catch let error {
    print(error.localizedDescription)
}

带有自定义对象数组的资源

输入 JSON

/**
{
    "data": {
        "type": "subscription",
        "id": "1",
        "attributes": {
            "title": "Very nice subscription!",
            "prices": [{
                "type:": "monthly",
                "value": "1"
            },
            {
                "type:": "onetime",
                "value": "10"
            }]
        }
    }
}
*/

@objcMembers class SubscriptionResource: Resource {
    
    var title: String?
    var prices: [Price]?

    override class var type: String {
        return "subscription"
    }

    override class var typesForKeys: [String : CustomObject.Type] {
        return ["prices": Price.self]
    }
}

struct Price: Codable {
    var value: String?
    var type: String?
}

许可证

IzzyParser 在 MIT 许可证下发布。 有关详细信息,请参阅 LICENSE