This repository was archived by the owner on Oct 6, 2020. It is now read-only.
File tree Expand file tree Collapse file tree 3 files changed +52
-21
lines changed Expand file tree Collapse file tree 3 files changed +52
-21
lines changed Original file line number Diff line number Diff line change 1
1
# JSONLoader
2
2
3
- A description of this package.
3
+ A simple library to quickly load JSON from your local bundle to a ` Codable ` object.
4
+
5
+ ## How to use
6
+ Simply define your ` struct ` as ` Codable ` and then when you need to map your JSON file to that object just call the ` load ` function.
7
+
8
+ ## Example
9
+ Say you had a JSON file named ` people.json ` like this:
10
+ ```
11
+ [
12
+ {
13
+ "id": 1,
14
+ "name": "Jane"
15
+ },
16
+ {
17
+ "id": 2,
18
+ "name": "John"
19
+ }
20
+ ]
21
+ ```
22
+ Now you need a data model like so:
23
+ ```
24
+ struct Person: Codable {
25
+ var id:Int
26
+ var name:String
27
+ }
28
+ ```
29
+ Now you all you need to do to populate a array of these is call the load method:
30
+
31
+ ```
32
+ var people:[Person] = JSONLoader.load("people")
33
+ ```
Original file line number Diff line number Diff line change 1
1
import Foundation
2
-
3
- public func load< T: Decodable > ( _ filename: String , as type: T . Type = T . self) -> T {
4
- let data : Data
5
- guard let file = Bundle . main. url ( forResource: filename, withExtension: nil )
6
- else {
7
- fatalError ( " Couldn't find \( filename) in main bundle. " )
2
+ class JSONLoader {
3
+ public func load< T: Decodable > ( _ filename: String , as type: T . Type = T . self) -> T {
4
+ let data : Data
5
+ guard let file = Bundle . main. url ( forResource: filename, withExtension: " json " )
6
+ else {
7
+ fatalError ( " Couldn't find \( filename) in main bundle. " )
8
+ }
9
+
10
+ do {
11
+ data = try Data ( contentsOf: file)
12
+ } catch {
13
+ fatalError ( " Couldn't load \( filename) from main bundle: \n \( error) " )
14
+ }
15
+
16
+ do {
17
+ let decoder = JSONDecoder ( )
18
+ return try decoder. decode ( T . self, from: data)
19
+ } catch {
20
+ fatalError ( " Couldn't parse \( filename) as \( T . self) \n \( error) " )
21
+ }
8
22
}
9
23
10
- do {
11
- data = try Data ( contentsOf: file)
12
- } catch {
13
- fatalError ( " Couldn't load \( filename) from main bundle: \n \( error) " )
14
- }
15
-
16
- do {
17
- let decoder = JSONDecoder ( )
18
- return try decoder. decode ( T . self, from: data)
19
- } catch {
20
- fatalError ( " Couldn't parse \( filename) as \( T . self) \n \( error) " )
21
- }
22
24
}
23
-
Original file line number Diff line number Diff line change @@ -6,7 +6,7 @@ final class JSONLoaderTests: XCTestCase {
6
6
// This is an example of a functional test case.
7
7
// Use XCTAssert and related functions to verify your tests produce the correct
8
8
// results.
9
- XCTAssertEqual ( JSONLoader ( ) . text , " Hello, World! " )
9
+
10
10
}
11
11
12
12
static var allTests = [
You can’t perform that action at this time.
0 commit comments