FreeformJSON 是一个小型数据结构,允许您以类型安全的方式创建和/或访问自由格式的 JSON 数据,同时仍然享受 Codable 协议的好处。 如果您想访问模型的某些部分,但不希望为它创建 class
/struct
,这会非常有用。
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"]
]
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 平台
只需将 JSON.swift
拖放到您自己的项目中的任何位置即可。
下载 repo,将 FreeformJSON.xcodeproj
拖到您自己的项目中,并链接到适合您平台的 target。
在您的 Podfile
中
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
target 'TargetName' do
use_frameworks!
pod 'FreeformJSON'
end
在您的 Cartfile
中
github "fabiorodella/FreeformJSON"
在您的 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"]),
]
)