LCJSONFormatter

這是一個(gè)純粹的swift版本的JSON轉(zhuǎn)模型工具。就像MJExtension一樣,在swift中,我們用Argo.
樣例JSON1,以字典開(kāi)始:
{
"id": 1,
"name": "JohnSnow",
"dic": [
{
"key": "hello world",
"value": "where are you"
},
{
"key": "hello world",
"value": "where are you"
}
],
"commentsInfo": {
"id": 100,
"value": "good man"
},
"price": 4.39,
"woman": false,
"optionalString": null,
"optionalArray": [ ]
}
樣例JSON2,以數(shù)組開(kāi)始:
[
{
"id": 1,
"name": "JohnSnow",
"dic": [
{
"key": "hello world",
"value": "where are you"
},
{
"key": "hello world",
"value": "where are you"
}
]
},
{
"id": 1,
"name": "JohnSnow",
"dic": [
{
"key": "hello world",
"value": "where are you"
},
{
"key": "hello world",
"value": "where are you"
}
]
}
]
使用
Alcatraz中搜索LCJSONFormatter,重啟Xcode.
在swift文件中,呼出LCJSONFormatter窗口。將上面的JSON粘貼進(jìn)去。一路回車(chē)就行了。
最后,轉(zhuǎn)換后的文件如下:
//對(duì)于樣例1,以字典開(kāi)始
import UIKit
import Argo
import Curry
struct LCJSONFormatterDemo: Decodable {
let optionalString: String?
let id: Int
let price: Double
let optionalArray: [String]?
let dic: [Dic]
let commentsInfo: Commentsinfo
let woman: Bool
let name: String
static func decode(json: JSON) -> Decoded<LCJSONFormatterDemo> {
return curry(self.init)
<^> json <|? "optionalString"
<*> json <| "id"
<*> json <| "price"
<*> json <||? ["optionalArray"]
<*> json <|| ["dic"]
<*> json <| "commentsInfo"
<*> json <| "woman"
<*> json <| "name"
}
}
struct Dic: Decodable {
let key: String
let value: String
static func decode(json: JSON) -> Decoded<Dic> {
return curry(self.init)
<^> json <| "key"
<*> json <| "value"
}
}
struct Commentsinfo: Decodable {
let id: Int
let value: String
static func decode(json: JSON) -> Decoded<Commentsinfo> {
return curry(self.init)
<^> json <| "id"
<*> json <| "value"
}
}
//對(duì)于樣例2,以字典開(kāi)始
import UIKit
import Argo
import Curry
struct LCJSONFormatterDemo: Decodable {
let lcArray: [Lcarray]
static func decode(json: JSON) -> Decoded<LCJSONFormatterDemo> {
return curry(self.init)
<^> json <|| ["lcArray"]
}
}
struct Lcarray: Decodable {
let id: Int
let name: String
let dic: [Dic]
static func decode(json: JSON) -> Decoded<Lcarray> {
return curry(self.init)
<^> json <| "id"
<*> json <| "name"
<*> json <|| ["dic"]
}
}
struct Dic: Decodable {
let key: String
let value: String
static func decode(json: JSON) -> Decoded<Dic> {
return curry(self.init)
<^> json <| "key"
<*> json <| "value"
}
}