FreeformJSON:具有 Codable 支持的 Swift 类型安全自由格式 JSON 数据结构

License Platform CocoaPods Compatible Carthage Compatible Swift PM Compatible Build Status

FreeformJSON 是一个小型数据结构,允许您以类型安全的方式创建和/或访问自由格式的 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 平台

安装

单文件

只需将 JSON.swift 拖放到您自己的项目中的任何位置即可。

框架

下载 repo,将 FreeformJSON.xcodeproj 拖到您自己的项目中,并链接到适合您平台的 target。

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"]),
    ]
)