Code Monkey home page Code Monkey logo

myjsonable's Introduction

MyJSONable

JSON to Model, Model to JSON

Version

1.0.0

  • 基础功能 JSONable + JSONableMacro宏

1.1.0

news:

  • 子类继承专用宏JSONableSubclassMacro

changes:

  • JSONable协议拆分为KeyPathListProvider & JSONEncodeDecode
  • KeyPathListProvider将原有的static var allKeyPathList改为func allKeyPathList()
  • JSONableKeyPathObject去除了泛型,keyPath需要补全Root类型,例如\.name改为\XXX.name

issues:

  • class继承时,混用父类keyPath和子类keyPath,导致encodeJsonExcludedKeys无法正确排除

1.1.1

changes:

  • ValueTypeKeyPathProvider名称标记为废弃
  • macro实现去除ExtensionMacro协议实现

1.1.2

news:

  • 新增自定义key宏JSONableCustomKey,标记于属性前面

changes & fixed:

  • 修复了连续定义的属性keyPathList代码生成缺少变量,例如var a, b, c, d: String?

1.1.3

news:

  • 新增Date属性转化宏JSONableDateMapper,以支持unix时间戳(秒和毫秒)

Implement

通过简单的keyPaths遍历实现property写入

Decoding Json values to Model properties via keyPaths

Install

use swift package manager add this git

Documentation

Basic 基础用法

import MyJSONable

@JSONableMacro
struct Animal_M: JSONable {
    var boolVal: Bool = false
    var doubleVal: Double = 0
    var intVal: Int = 0
    var stringVal: String = ""
    var child3: [String: Any] = [:]
}

var animal = Animal2()
let json: [String: Any] = [
    "boolVal": true,
    "doubleVal": 3.14,
    "intVal": 314,
    "stringVal": "New Dog",
    "child": [
        "age2": 100,
        "name2": "New Cow"
    ],
    "child3": [
        "age2": 22,
        "name2": "New 222",
        "stringList": [
            "a", "b", "c",
        ],
    ],
]

animal.decodeFromJson(json: json)

let jsonString = animal.encodeToJsonString()

use @JSONableMacro macro to auto generate allKeyPathList function, otherwise, write this manually

class

must be final class

@JSONableMacro
final class ChildAnimal2: MyJSONable.JSONable {
    var age2: Int = 0
    var name2: String = ""
    var stringList: [String]?
}

class inherit

if your superclass is JSONable, use macro JSONableSubclassMacro

@JSONableMacro
class Person: JSONable {
    var boolVal: Bool?
    var doubleVal: Double?
    var intVal: Int?
    var stringVal: String?
    
    required init() {
    }
}

@JSONableSubclassMacro
class Student: Person {
    var name: String?
    var id: Int = 0
}

Enum 枚举类型

enum type from string or int

enum EnumStringAnimal: String, JSONableEnum {
    case cat = "cat"
    case dog = "dog"
}

enum EnumIntAnimal: Int, JSONableEnum {
    case cat = 1
    case dog = 2
}

Custom key name 自定义json的key值

Different key from json example using key "cccc" for property var children2

func customKeyPathList() -> [JSONableKeyPathObject] { 
    return [
        .init(name: "cccc", keyPath: \Animal2.children2)
    ]
}

or simple style:

@JSONableCustomKey("cccc")
var children2: Child?

Custom value mapper 自定义类型的转化

mapper JsonValue <--> ModelValue

example var birthday: Date?

func customKeyPathList() -> [JSONableKeyPathObject] { 
    return [
        .init(name: "birthday", keyPath: \Animal2.birthday, customGet: { someDate in
            return someDate?.timeIntervalSince1970
        }, customSet: { someI in
            if let interv = someI as? TimeInterval {
                return Date(timeIntervalSince1970: interv)
            }
            return nil
        }),
    ]
}

Exclude Keys to JSON 输出Json时排除特定key

example: exclude key price while encodeToJSON

@JSONableMacro
struct Animal_M: JSONable {
    var age: Int = 0
    var name: String = "Cat"
    var price: String = "Value not to JSON"
    
    func encodeJsonExcludedKeys() -> Set<AnyKeyPath> {
        return [\Animal_M.price,]
    }
}

Date Mapper 日期转换

example: map unixTimeStamp to Date

@JSONableMacro
struct DateTest: JSONable {
    @JSONableDateMapper("date1000", mapper: .unixTimeStampMilliSecond)
    var date2: Date? // with custom key "date1000"
    @JSONableDateMapper("date0", mapper: .unixTimeStampSecond)
    var date: Date? // with custom key "date0"
    @JSONableDateMapper(mapper: .unixTimeStampSecond)
    var date3: Date? // with default key "date3" depends on name
}

for other mapper, you can add extension to JSONableMapper where T == Date

extension JSONableMapper where T == Date {
    public static let iso8601 = JSONableMapper<Date> { any in
        // return your date
    } encode: { date in
        // return your value
    }
}

myjsonable's People

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.