目录
目录README.md

CircleCI CocoaPods compatible Swift Package Manager compatible

JSONCodable is a lightweight library for decoding/encoding all basic JSON types in a type-safe manner.

  • Support for all basic JSON types (string, integer, number, boolean, null, dictionary and array)
  • Extensions to convert [String: JSONCodable] to [String: Any] and back

Installation

To integrate using Apple’s Swift package manager, add the following as a dependency to your Package.swift:

.package(url: "https://github.com/finn-no/JSONCodable.git", .upToNextMajor(from: "1.0.0"))

JSONCodable is also available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'JSONCodableType'

Usage

Encoding JSONCodable values from a dictionary:

let dictionary: [String: JSONCodable] = [
  "null": .null,
  "integer": 1,
  "number": 1.1,
  "boolean": true,
  "string": "test",
  "array": ["item1", "item2"],
  "dictionary": ["key1": "value1", "key2": "value2"]
]

let data = try JSONEncoder().encode(dictionary)

Decoding JSONCodable values:

let jsonString = """
  {
      "null": null,
      "integer": 1,
      "number": 1.1,
      "boolean": true,
      "string": "test",
      "array": ["item1", "item2"],
      "dictionary": { "key1": "value1", "key2": "value2" }
  }
  """
let data = jsonString.data(using: .utf8)!
let dictionary = try JSONDecoder().decode([String: JSONCodable].self, from: data)
let anyDictionary: [String: Any] = jsonCodableDictionary.mapAnyValues() 

Working with custom Codable types:

struct User: Codable {
  let name: String
  let meta: [String: JSONCodable]
}

let user = User(name: "Test", meta: ["string": "value", "integer": 1])
let data = try JSONEncoder().encode(user)
let decodedUser = try JSONDecoder().decode(User.self, from: data)
关于
38.0 KB
邀请码