Created
December 21, 2017 06:48
-
-
Save KatagiriSo/4d39fed7efb96d0cc49e873f3595cd0b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// CodableTS | |
// | |
// Created by KatagiriSo on 2017/12/21. | |
// Copyright © 2017年 katagiri. All rights reserved. | |
// | |
import Foundation | |
//print("Hello, World!") | |
let rawJson = """ | |
{ | |
"hello": "world", | |
"key": null, | |
"int": 12345, | |
"hogetype" : "box", | |
"double": 9876.543, | |
"url": "http://timers-inc.com/", | |
"nested" : { | |
"hoge" : "hoge!", | |
"hogehoge" : "hoge2!" | |
}, | |
"arrayNest" : [ | |
{ | |
"hoge" : "nestarrayhoge1", | |
"hogehoge" : "1x" | |
}, | |
{ | |
"hoge" : "nestarrayhoge2", | |
"hogehoge" : "2x" | |
} | |
] | |
} | |
""" | |
extension CustomStringConvertible where Self : Encodable { | |
func desc() -> String { | |
let encoder = JSONEncoder() | |
encoder.outputFormatting = .prettyPrinted | |
let data_ = try? encoder.encode(self) | |
guard let data = data_ else { | |
return "" | |
} | |
guard let str = String(data: data, encoding: .utf8) else { | |
return "" | |
} | |
return str | |
} | |
} | |
struct NewJson: Codable, CustomStringConvertible { | |
let hello: String | |
let key: String? | |
let int: Int | |
let double: Double | |
let url: URL | |
let op : Int = 0 // default | |
let nested:Nested | |
let arrayNest:[Nested]? | |
let hogetype:HogeType | |
enum HogeType : String, Codable { | |
case box = "box" | |
case line = "line" | |
} | |
class Nested : Codable, CustomStringConvertible { | |
let hoge:String? | |
let fuga:String? | |
let poi:Int = 5 // JSONと無関係 | |
var description: String { | |
get { | |
return desc() | |
} | |
} | |
enum CodingKeys: String, CodingKey { | |
case hoge | |
case fuga = "hogehoge" | |
} | |
} | |
var description: String { | |
get { | |
return desc() | |
} | |
} | |
} | |
guard let data = rawJson.data(using: .utf8) else { | |
print("data is nil") | |
fatalError() | |
} | |
let decoder = JSONDecoder() | |
do { | |
let newJson:NewJson = try decoder.decode(NewJson.self, from: data) | |
print("newjson \(newJson)") | |
} catch let e { | |
print("json decode error \(e)") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment