Skip to content

Instantly share code, notes, and snippets.

View Ravi61's full-sized avatar

Ravi Kumar Aggarwal Ravi61

View GitHub Profile
@Ravi61
Ravi61 / Basic.json
Last active July 12, 2017 17:57
Basic json
{
"name": "Luke Freaking Skywalker",
"age": 22,
"address": "Moisture Farm, Tatooine"
}
@Ravi61
Ravi61 / Encode.swift
Last active July 12, 2017 17:46
Encoding Code for
let encoder = JSONEncoder()
do {
let data = try encoder.encode(BattleShip)
print(String(data: data, encoding: .utf8)!)
} catch {
print("error in converting the model")
}
@Ravi61
Ravi61 / BattleShip.json
Last active July 12, 2017 17:29
Battleship JSON for
{
"name": "Death Star",
"model": "DS-1 Orbital Battle Station",
"manufacturer": "Imperial Department of Military Research, Sienar Fleet Systems",
"hyperdrive_rating": 4.0,
"starship_class": "Deep Space Mobile Battlestation",
"created": "2014-12-10T16:36:50.509000Z",
"url": "http://swapi.co/api/starships/9/"
}
@Ravi61
Ravi61 / Person.swift
Last active July 12, 2017 17:52
Basic person model
struct Person: Codable {
var name: String
var age: Int
var address: String
}
@Ravi61
Ravi61 / Decode.swift
Last active July 12, 2017 17:58
Decoding code for
// let jsonData = Person JSON
let decoder = JSONDecoder()
do {
let model = try decoder.decode(Person.self, from: jsonData)
print(model)
} catch {
print("Error parsing JSON")
}
@Ravi61
Ravi61 / BattleShip.swift
Last active July 12, 2017 17:33
BattleShip model without URL and Date usage
struct BattleShip: Codable {
var name: String
var model: String
var manufacturer: String
var hyperdriveRating: Double
var starshipClass: String
var created: String
var url: String
enum CodingKeys: String, CodingKey {
@Ravi61
Ravi61 / BattleshipNested.json
Last active July 12, 2017 19:38
Battleship JSON with Array and Objects
{
"name": "Death Star",
"created": "2014-12-10T16:36:50.509000Z",
"url": "http://swapi.co/api/starships/9/",
"films": [
{
"name": "Star Wars: Episode IV – A New Hope",
"director": "George Lucas"
},
{
@Ravi61
Ravi61 / BattleshipNested.swift
Last active July 12, 2017 19:37
Battleship model with object and array
struct BattleShip: Codable {
var name: String
var created: String
var url: String
struct Film: Codable {
var name: String
var director: String
}
var films: [Film]
}
@Ravi61
Ravi61 / RootDecode.swift
Created July 12, 2017 18:18
Decoding root level array
let decoder = JSONDecoder()
do {
let films = try decoder.decode([Film].self, from: jsonData)
} catch {
print("parse error")
}
@Ravi61
Ravi61 / BattleshipDate.swift
Last active July 13, 2017 17:43
Battleship model for encoding/decoding dates
struct BattleShip: Codable {
//...
var created: Date
//...
}
//...
// Let's decode
let decoder = JSONDecoder()
do {