Build Status codecov.io CocoaPods Compatible Swift Package Manager Compatible Platform support License MIT

CoreJSON

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
            ]
        ]

Foundation

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)