• HandyJSON的用法 swift


    下载地址

    https://github.com/alibaba/HandyJSON

    文档详尽,请看GitHub里的文档

    model需要遵循 HandyJSON 协议,class 类需要实现 init方法,Struct 结构体不需要实现 init方法

    1.json 串转 model

    class BasicTypes: HandyJSON {
        var int: Int = 2
        var doubleOptional: Double?
        var stringImplicitlyUnwrapped: String!
    
        required init() {}
    }
    
    let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
    if let object = BasicTypes.deserialize(from: jsonString) {
        print(object.int)
        print(object.doubleOptional!)
        print(object.stringImplicitlyUnwrapped)
    }

    2.json 串转 model 数组

    class Cat: HandyJSON {
        var name: String?
        var id: String?
    
        required init() {}
    }
    
    let jsonArrayString: String? = "[{\"name\":\"Bob\",\"id\":\"1\"}, {\"name\":\"Lily\",\"id\":\"2\"}, {\"name\":\"Lucy\",\"id\":\"3\"}]"
    if let cats = [Cat].deserialize(from: jsonArrayString) {
        cats.forEach({ (cat) in
            // ...
        })
    }

    3.字典转 model

    var dict = [String: Any]()
    dict["doubleOptional"] = 1.1
    dict["stringImplicitlyUnwrapped"] = "hello"
    dict["int"] = 1
    if let object = BasicTypes.deserialize(from: dict) {
        // ...
    }

    4.model 转字典

    model 转 json 串

    class BasicTypes: HandyJSON {
        var int: Int = 2
        var doubleOptional: Double?
        var stringImplicitlyUnwrapped: String!
    
        required init() {}
    }
    
    let object = BasicTypes()
    object.int = 1
    object.doubleOptional = 1.1
    object.stringImplicitlyUnwrapped = “hello"
    
    print(object.toJSON()!) // serialize to dictionary
    print(object.toJSONString()!) // serialize to JSON string
    print(object.toJSONString(prettyPrint: true)!) // serialize to pretty JSON string
  • 相关阅读:
    删除字符串组中相同元素,并删除值为空的元素 (转载,笔记)
    获取操作系统语言
    .net 传递中文参数解决办法
    古怪问题:vs2003程序 在繁体平台下控件位置发生变化
    Godaddy邮箱C#发送邮件设置
    无法显示隐藏文件的解决方法
    虚拟机文件
    sql 2000 修复问题
    看QQ是否在线
    sql 知识摘录
  • 原文地址:https://www.cnblogs.com/huangzs/p/16400809.html
Copyright © 2020-2023  润新知