HTML 为 Web 浏览器所做的事情,HAL 为应用程序所做。
HTML 为您提供标记信息的页面,以便向用户展示;HAL 为您提供标记的表示形式,供应用程序使用。应用程序可以轻松提取有关远程资源的信息,包括资源之间的关系。HAL 称之为表示形式,HTML 称之为网页;这些页面都包含指向其他页面的链接。HTML 旨在向人类展示信息。HAL 旨在向应用程序展示信息。
此框架提供了一套 Swift 类,用于渲染和解析资源表示形式,包括它们的链接、属性和嵌入资源的嵌套表示形式。
该框架允许您编码和解码 HAL 表示形式。表示形式在内部通过字典或 Swift 中的 [String: Any]
类型进行渲染和解析,但可以通过字典在其他类型之间进行编码。例如,您可以从 Representation
实例构建 JSON 字符串,反之亦然。
首先,您可以轻松构建资源表示形式,并使用链接、嵌入式表示形式和属性对其进行配置。以下示例构建了一个虚构的客户资源。
let representation = Representation()
.with(rel: Link.SelfRel, href: "https://example.com/api/customer/123456")
.with(name: "ns", ref: "https://example.com/apidocs/ns/" + NamespaceManager.Rel)
.with(name: "role", ref: "https://example.com/apidocs/role/" + NamespaceManager.Rel)
.with(link: Link(rel: "ns:parent", href: "https://example.com/api/customer/1234")
.with(name: "bob")
.with(title: "The Parent")
.with(hreflang: "en"))
.with(rel: "ns:users", href: "https://example.com/api/customer/123456?users")
.with(name: "id", value: 123456)
.with(name: "age", value: 33)
.with(name: "name", value: "Example Resource")
.with(name: "optional", value: true)
.with(name: "expired", value: false)
此摘录显示了级联 with
方法在配置表示形式中的使用。但是 Representation
和 Link
类也提供了更传统的方法来加载其属性值。
将表示形式转换为 JSON 非常容易。
try! representation.jsonString(options: .prettyPrinted)!
请注意 try
。如果 JSONSerialization
失败,转换为 JSON 会抛出错误。另请注意可选字符串结果的“bang”,如果 JSON 数据由于任何原因未能转换为 UTF-8 字符串,则可能会产生 nil
。
jsonString(options:)
方法生成一个包含 JSON 编码的超文本应用语言的字符串,如下所示
{
"optional" : true,
"age" : 33,
"name" : "Example Resource",
"id" : 123456,
"expired" : false,
"_links" : {
"self" : {
"href" : "https://example.com/api/customer/123456"
},
"curies" : [
{
"name" : "ns",
"templated" : true,
"href" : "https://example.com/apidocs/ns/{rel}"
},
{
"name" : "role",
"templated" : true,
"href" : "https://example.com/apidocs/role/{rel}"
}
],
"ns:parent" : {
"name" : "bob",
"title" : "The Parent",
"href" : "https://example.com/api/customer/1234",
"hreflang" : "en"
},
"ns:users" : {
"href" : "https://example.com/api/customer/123456?users"
}
}
}
请注意,该字符串没有转义正斜杠。
将此内容转换回表示形式也非常简单。假设 JSON 编码的字符串在一个名为 string
的变量中,则以下表达式从 JSON 字符串构造一个新的表示形式对象。
try! Representation.from(json: string.data(using: String.Encoding.utf8)!)
结果与原始结果匹配。当然,在实际应用中,您会捕获错误并保护可选值。
接口和实现很大程度上呼应了用 Java 编写的那些,但存在一些故意的偏差。
Swift 框架在命名中添加了一些一致性。“表示形式”(Representation)是用于描述表示某些远程资源的对象所使用的名称。“资源”(resource)一词描述的是实际的远程资源。表示形式仅表示资源;它们不是资源本身。
“currie” 的使用已被替换,因为它部分地与数学和计算机科学中柯里化和柯里化函数的概念重叠,而实际上术语“curie”仅指紧凑 URI。该首字母缩写词仅巧合地类似于单词“curry”(咖喱),一种美味的亚洲餐点。