CoreJSON 提供了一个简单的 JSON 数据模型,并在其之上提供了一系列实用工具。
CoreJSON 由多个模块组成
import CoreJSON
// CoreJson provides a very simple JSON data model
let simpleJson = JSON.array([
JSON.bool(true),
JSON.string("string"),
JSON.null,
JSON.number(.int(10)),
JSON.object([:])
])
// JSON is equatable and hashable
simpleJson == simpleJson // -> true
JSON.bool(true) == .null // -> false
simpleJson.hashValue // -> Some hash value
import CoreJSONLiterals
var json: JSON = [
"books": [
[
"name": "Sample Book",
"pages": 141,
"author": [
"firstName": "John",
"lastName": "Doe",
"age": 43
]
],
[
"name": "How to not create code examples",
"pages": 53,
"author": [
"firstName": "Mike",
"lastName": "Miller",
"age": 27
]
]
]
]
import CoreJSONSubscript
var firstBook = json["books"]?[0] // -> JSON.object(...)
let bookName = firstBook?["name"] // -> JSON.string("Sample Book")
var jsonCopy = json
jsonCopy["books"]?[1] = .string("changed")
jsonCopy["books"]?[1] // -> JSON.string("changed")
import CoreJSONConvenience
bookName?.stringValue // -> "Sample Book"
firstBook?["pages"]?.intValue // -> 141
firstBook?["pages"]?.intValue = 100
firstBook?["pages"]?.intValue // -> 100
import CoreJSONPointer
json["/books/1/author/lastName" as JSONPointer]?.stringValue
json["/books/-" as JSONPointer] = [
"name": "JSON for dummies",
"pages": 612,
"author": [
"firstName": "Richard",
"lastName": "Roe",
"age": 34
]
]
import CoreJSONFoundation
import Foundation
let jsonData = try! JSONSerialization.data(withJSONObject: json.toFoundation(), options: .prettyPrinted)
String(data: jsonData, encoding: .utf8) // -> JSON string
let parsedJson = try! JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
try! JSON(foundation: parsedJson)