• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

kakaopensource/KakaJSON: Fast conversion between JSON and model in Swift.

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

kakaopensource/KakaJSON

开源软件地址:

https://github.com/kakaopensource/KakaJSON

开源编程语言:

Swift 99.5%

开源软件介绍:

KakaJSON

pod Carthage compatible SwiftPM compatible

Fast conversion between JSON and model in Swift.

  • Convert model to JSON with one line of code.(一行代码Model转JSON)
  • Convert JSON to Model with one line of code.(一行代码JSON转Model)
  • Archive\Unarchive object with one line of code.(一行代码实现常见数据的归档\解档)

中文教程

Integration

CocoaPods

pod 'KakaJSON', '~> 1.1.2' 

Carthage

github "kakaopensource/KakaJSON" ~> 1.1.2

Swift Package Manager

To use Swift Package Manager, you should update to Xcode 11.

  • Open your project.
  • Click File tab
  • Select Swift Packages
  • Add Package Dependency, enter KakaJSON repo's URL

Or you can login Xcode with your GitHub account. just search KakaJSON.

Usages

Coding

// file path (can be String or URL)
let file = "/Users/mj/Desktop/test.data"

/****************** String ******************/
let string1 = "123"
// wrtite String to file
write(string1, to: file)
// read String from file
let string2 = read(String.self, from: file)
XCTAssert(string2 == string1)
// read Int from file
XCTAssert(read(Int.self, from: file) == 123)

/****************** Date ******************/
let date1 = Date(timeIntervalSince1970: 1565922866)
// wrtite Date to file
write(date1, to: file)
 
// read Date from file
let date2 = read(Date.self, from: file)
XCTAssert(date2 == date1)
 
// read Int from file
XCTAssert(read(Int.self, from: file) == 1565922866)

/****************** Array ******************/
let array1 = ["Jack", "Rose"]
// wrtite [String] to file
write(array1, to: file)
 
// read [String] from file
let array2 = read([String].self, from: file)
XCTAssert(array2 == array1)
// Also support Set\Dictionary

/****************** Model ******************/
struct Book: Convertible {
    var name: String = ""
    var price: Double = 0.0
}
 
struct Car: Convertible {
    var name: String = ""
    var price: Double = 0.0
}
 
struct Dog: Convertible {
    var name: String = ""
    var age: Int = 0
}
 
struct Person: Convertible {
    var name: String = "Jack"
    var car: Car? = Car(name: "Bently", price: 106.666)
    var books: [Book]? = [
        Book(name: "Fast C++", price: 666.6),
        Book(name: "Data Structure And Algorithm", price: 666.6),
    ]
    var dogs: [String: Dog]? = [
        "dog0": Dog(name: "Wang", age: 5),
        "dog1": Dog(name: "ErHa", age: 3),
    ]
}
 
// wrtite Person to file
write(Person(), to: file)
 
// read Person from file
let person = read(Person.self, from: file)
 
XCTAssert(person?.name == "Jack")
XCTAssert(person?.car?.name == "Bently")
XCTAssert(person?.car?.price == 106.666)
XCTAssert(person?.books?.count == 2)
XCTAssert(person?.dogs?.count == 2)

/****************** Model Array ******************/
struct Car: Convertible {
    var name: String = ""
    var price: Double = 0.0
}
 
let models1 = [
    Car(name: "BMW", price: 100.0),
    Car(name: "Audi", price: 70.0)
]
// wrtite [Car] to file
write(models1, to: file)
 
// read [Car] from file
let models2 = read([Car].self, from: file)
XCTAssert(models2?.count == models1.count)
XCTAssert(models2?[0].name == "BMW")
XCTAssert(models2?[0].price == 100.0)
XCTAssert(models2?[1].name == "Audi")
XCTAssert(models2?[1].price == 70.0)

/****************** Model Set ******************/
struct Car: Convertible, Hashable {
    var name: String = ""
    var price: Double = 0.0
}
 
let models1: Set<Car> = [
    Car(name: "BMW", price: 100.0),
    Car(name: "Audi", price: 70.0)
]
 
// wrtite Set<Car> to file
write(models1, to: file)
 
// read Set<Car> from file
let models2 = read(Set<Car>.self, from: file)!
XCTAssert(models2.count == models1.count)
for car in models2 {
    XCTAssert(["BMW", "Audi"].contains(car.name))
    XCTAssert([100.0, 70.0].contains(car.price))
}

/****************** Model Dictionary ******************/
struct Car: Convertible {
    var name: String = ""
    var price: Double = 0.0
}
 
let models1 = [
    "car0": Car(name: "BMW", price: 100.0),
    "car1": Car(name: "Audi", price: 70.0)
]
 
// wrtite [String: Car] to file
write(models1, to: file)
 
// read [String: Car] from file
let models2 = read([String: Car].self, from: file)
XCTAssert(models2?.count == models1.count)
 
let car0 = models2?["car0"]
XCTAssert(car0?.name == "BMW")
XCTAssert(car0?.price == 100.0)
 
let car1 = models2?["car1"]
XCTAssert(car1?.name == "Audi")
XCTAssert(car1?.price == 70.0)

JSON To Model_01_Basic Usage

Simple Model

struct Cat: Convertible {
    var name: String = ""
    var weight: Double = 0.0
}

// json can also be NSDictionary, NSMutableDictionary
let json: [String: Any] = [
    "name": "Miaomiao",
    "weight": 6.66
]

let cat1 = json.kj.model(Cat.self)
XCTAssert(cat1.name == "Miaomiao")
XCTAssert(cat1.weight == 6.66)

// you can call global function `model`
let cat2 = model(from: json, Cat.self)

// support type variable
var type: Convertible.Type = Cat.self
let cat3 = json.kj.model(type: type) as? Cat
let cat4 = model(from: json, type: type) as? Cat

Class Type

class Cat: Convertible {
    var weight: Double = 0.0
    var name: String = ""
    // The protocol `Convertible` required an init constructor
    // for initializing an instance completely.
    required init() {}
}
let json = ...
let cat = json.kj.model(Cat.self)

// a class inherit from NSObject
class Person: NSObject, Convertible {
    var name: String = ""
    var age: Int = 0
    // must add `override` because NSObject has `init`
    required override init() {}
}
let person = json.kj.model(Person.self)

struct Dog: Convertible {
    var weight: Double = 0.0
    var name: String = ""
    // This struct don't need to implement init because compiler generates init for it
}

struct Pig: Convertible {
    var weight: Double
    var name: String
    // This struct need to implement init to initialize all the stored properties.
    init() {
        name = ""
        weight = 0.0
    }
}

Inheritance

class Person: Convertible {
    var name: String = ""
    var age: Int = 0
    required init() {}
}
 
class Student: Person {
    var score: Int = 0
    var no: String = ""
}
 
let json: [String: Any] = [
    "name": "jack",
    "age": 18,
    "score": 98,
    "no": "9527"
]
 
let student = json.kj.model(Student.self)

let

struct Cat: Convertible {
    // let of integer type is very restricted in release mode
    // please user `private(set) var` instead of `let`
    private(set) var weight: Double = 0.0
    let name: String = ""
}
let json = ...
let cat = json.kj.model(Cat.self)

NSNull

struct Cat: Convertible {
    var weight: Double = 0.0
    var name: String = "xx"
    var data: NSNull?
}

let json: [String: Any] = [
    "name": NSNull(),
    "weight": 6.6,
    "data": NSNull()
]

let cat = json.kj.model(Cat.self)
// convert failed, keep default value
XCTAssert(cat.name == "xx")
XCTAssert(cat.weight == 6.6)
XCTAssert(cat.data == NSNull())

JSONString

// jsonString can alse be NSString, NSMutableString
let jsonString = """
{
    "name": "Miaomiao",
    "weight": 6.66
}
"""
 
let cat1 = jsonString.kj.model(Cat.self)
let cat2 = model(from: jsonString, Cat.self)

var type: Convertible.Type = Cat.self
let cat3 = jsonString.kj.model(type: type) as? Cat
let cat4 = model(from: jsonString, type: type) as? Cat

JSONData

// jsonData can alse be NSData, NSMutableData
let jsonData = """
{
    "name": "Miaomiao",
    "weight": 6.66
}
""".data(using: .utf8)!
 
let cat1 = jsonData.kj.model(Cat.self)
let cat2 = model(from: jsonData, Cat.self)

var type: Convertible.Type = Cat.self
let cat3 = jsonData.kj.model(type: type) as? Cat
let cat4 = model(from: jsonData, type: type) as? Cat

Nested Model 1

// let all the models comform to Convertible

struct Book: Convertible {
    var name: String = ""
    var price: Double = 0.0
}
 
struct Car: Convertible {
    var name: String = ""
    var price: Double = 0.0
}
 
struct Dog: Convertible {
    var name: String = ""
    var age: Int = 0
}
 
struct Person: Convertible {
    var name: String = ""
    var car: Car?
    var books: [Book]?
    var dogs: [String: Dog]?
}
 
let json: [String: Any] = [
    "name": "Jack",
    "car": ["name": "BMW7", "price": 105.5],
    "books": [
        ["name": "Fast C++", "price": 666.6],
        ["name": "Data Structure And Algorithm", "price": 1666.6]
    ],
    "dogs": [
        "dog0": ["name": "Larry", "age": 5],
        "dog1": ["name": "ErHa", "age": 2]
    ]
]
 
let person = json.kj.model(Person.self)
XCTAssert(person.car?.name == "BMW7")
XCTAssert(person.books?[1].name == "Data Structure And Algorithm")
XCTAssert(person.dogs?["dog0"]?.name == "Larry")

Nested Model 2


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap