FreeformJSON:带有Codable支持的类型安全freeform JSON数据结构
FreeformJSON是一个小型数据结构,允许您以类型安全的方式创建和/或访问freeform JSON数据,同时仍然享受Codable协议的便利。如果您想访问模型的部分内容,但又不想为此创建一个`class`/`struct`,这将非常有用。
示例
在其他的Codable数据结构中使用
import FreeformJSON
struct Post: Codable {
let name: String
let embeddedContent: JSON
}
...
let link = post.embeddedContent["origin"]["link"].string
从字面值创建
let post: JSON = [
"name": "My Post",
"rating": 4,
"hidden": false,
"tags": ["tag1", "tag2"]
]
Encodable
类型创建
从任何 struct Post: Encodable {
let name: String
let rating: Double
let hidden: Bool
let tags: [String]
}
let post = Post(name: "My Post", rating: 4.0, hidden: false, tags: ["tag1", "tag2"])
let postJson = try JSON.fromEncodable(post)
let name = post["name"].string // Optional("My Post")
安全或原始属性访问
let name = post["name"].string // Optional("My Post")
let notAString = post["rating"].string // nil
let nonExisting = post["nonExisting"].string // nil
let tag = post["tags"][0] // Optional("tag1")
let rawTags = post["tags"].rawValue! as! [String] // ["tag1", "tag2"]
要求
FreeformJSON 与 Swift 4.x 及更高版本兼容。支持所有 Apple 平台
- iOS 9.0+
- macOS 10.9+
- watchOS 2.0+
- tvOS 9.0+
安装
单个文件
只需将 JSON.swift
放置在自己的项目中的任何位置。
框架
下载仓库,将 FreeformJSON.xcodeproj
拖入您的项目,并为您的平台链接相应的目标。
CocoaPods
在你的 Podfile
中
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
target 'TargetName' do
use_frameworks!
pod 'FreeformJSON'
end
Carthage
在你的 Cartfile
中
github "fabiorodella/FreeformJSON"
Swift Package Manager
在你的 Package.swift
中
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "TargetName",
dependencies: [
.package(url: "https://github.com/fabiorodella/FreeformJSON.git", from: "1.0.0"),
],
targets: [
.target(
name: "TargetName",
dependencies: ["FreeformJSON"]),
]
)