https://github.com/tbxark/jsonelement
JSONElement makes it easier and safer to use JSON
https://github.com/tbxark/jsonelement
json-mapper
Last synced: 5 months ago
JSON representation
JSONElement makes it easier and safer to use JSON
- Host: GitHub
- URL: https://github.com/tbxark/jsonelement
- Owner: TBXark
- License: mit
- Created: 2016-11-08T09:09:13.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2022-05-18T07:29:18.000Z (over 3 years ago)
- Last Synced: 2024-04-26T12:01:19.100Z (over 1 year ago)
- Topics: json-mapper
- Language: Swift
- Homepage:
- Size: 44.9 KB
- Stars: 6
- Watchers: 4
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# JSONElement
`JSONElement` is a simple, fast and secure way to access Json.
Because `Any` can't be used in `Codable`, it can be replaced with `JSONElement` for properties of type `Any`.
## Installation
### Swift Package Manager
Add the dependency in your `Package.swift` file:
```swift
let package = Package(
name: "myproject",
dependencies: [
.package(url: "https://github.com/TBXark/JSONElement.git", .upToNextMajor(from: "1.4.0"))
],
targets: [
.target(
name: "myproject",
dependencies: ["JSONElement"]),
]
)
```### Carthage
Add the dependency in your `Cartfile` file:
```bash
github "TBXark/JSONElement" ~> 1.4.0.
```### CocoaPods
Add the dependency in your `Podfile` file:
```ruby
pod 'JSONElement'
```# Example
```swift
final class JSONElementTests: XCTestCase {
struct Human: Codable {
let age: Int
let name: String
let height: Double
let extra: JSONElement // Any?
}
let dict = ["data": ["man": ["age": 10, "name": "Peter", "height": 180.0, "extra": [123, "123", [123], ["123": 123], true]]]]
func testJSONElement() throws {let json = try JSONElement(rawJSON: dict)
// 使用dynamicMemberLookup直接获取
XCTAssertEqual(json.data.man.age.intValue, 10)// 使用Key获取
XCTAssertEqual(json["data"]["man"]["height"].decimalValue, 180.0)// 使用Keypath获取
XCTAssertEqual(json[keyPath: "data.man.name"].stringValue, "Peter")
// 将不确定类型对象解析为JSONElement
XCTAssertEqual(json.data.man.extra.arrayValue?.first?.intValue , 123)
XCTAssertEqual(try? json.data.man.extra.arrayValue?.last?.as(Bool.self), true)}
func testJSONMapper() throws {
let json = JSONMapper(dict)
// 使用 dynamicMemberLookup 获取
XCTAssertEqual(json.data.man.height.as(Double.self), 180.0)// 使用Key获取
XCTAssertEqual(json["data"]["man"]["age"].intValue, 10)
XCTAssertEqual(json["data"]["man"]["height"].as(Double.self), 180.0)// 使用Keypath获取
XCTAssertEqual(json[keyPath: "data.man.name"].as(String.self), "Peter")// 将不确定类型对象解析为JSONElement
XCTAssertEqual(try? json[keyPath: "data.man.extra"].as(JSONElement.self)?.arrayValue?.last?.as(Bool.self), true)}
static var allTests = [
("testJSONElement", testJSONElement)
("testJSONMapper", testJSONMapper),
]
}```