Application of HandyJSON and SwiftyJSON

Posted by phpnewbie81 on Thu, 11 Jul 2019 00:42:00 +0200

1. Application of HandyJSON

In order to achieve serialization and deserialization through HandyJSON, we must implement HandyJSON protocol, which does not need to inherit NSObject objects, and implement public init(){} method.

Serialization and deserialization support struct and enumerate types.

HandyJSON supports non-basic types

    var bool: Bool = true
    var intOptional: Int?
    var doubleImplicitlyUnwrapped: Double!
    var anyObjectOptional: Any?

    var arrayInt: Array<Int> = []
    var arrayStringOptional: Array<String>?
    var setInt: Set<Int>?
    var dictAnyObject: Dictionary<String, Any> = [:]

    var nsNumber = 2
    var nsString: NSString?

1.1 deserialization

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)
}

// Several serialization methods provided by HandyJSON
let person = SOHomeModel.deserialize(from: <#T##NSDictionary?#>)
let person = SOHomeModel.deserialize(from: <#T##NSDictionary?#>, designatedPath: <#T##String?#>)
let person = SOHomeModel.deserialize(from: <#T##String?#>)
let person = SOHomeModel.deserialize(from: <#T##String?#>, designatedPath: <#T##String?#>)
let persons = [SOHomeModel].deserialize(from: <#T##String?#>)
let persons = [SOHomeModel].deserialize(from: <#T##String?#>, designatedPath: <#T##String?#>)

1.2 serialization

Serialization, support serialization into strings, dictionary.

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

1.3 Analytical paths can be specified

let jsonString = "{\"code\":200,\"msg\":\"success\",\"data\":{\"cat\":{\"id\":12345,\"name\":\"Kitty\"}}}"

if let cat = Cat.deserialize(from: jsonString, designatedPath: "data.cat") {
    print(cat.name)
}

Note that if the properties of Model are not primitive or collection types, then it must be a type subject to the HandyJSON protocol. If it is a generic set type, then the generic argument is required to be a basic type or a type subject to the HandyJSON protocol.

1.4 HandyJSON supports custom parsing rules

I haven't seen it yet. I can't use it yet.

1.5 Excludes specified attributes

If there are non-basic fields in the Model that cannot implement the HandyJSON protocol for some reasons, or enumeration fields of the HandyJSONEnum protocol, or that do not want deserialization to affect a field, it can be excluded from the mapping function. If not, undefined behavior may occur. (Actually, this is not very clear, that is to say, if you don't want serialization to affect a field, ignore it in the mapping method? Tests find that ignoring it will assign values as well.)

class NotHandyJSONType {
    var dummy: String?
}

class Cat: HandyJSON {
    var id: Int64!
    var name: String!
    var notHandyJSONTypeProperty: NotHandyJSONType?
    var basicTypeButNotWantedProperty: String?

    required init() {}

    func mapping(mapper: HelpingMapper) {
        mapper >>> self.notHandyJSONTypeProperty
        mapper >>> self.basicTypeButNotWantedProperty
    }
}

let jsonString = "{\"name\":\"cat\",\"id\":\"12345\"}"

if let cat = Cat.deserialize(from: jsonString) {
    print(cat)
}

2. Application of Swifty JSON

// Initialization
let json = JSON(data: jsonData)
if let number = json[0]["phones"][0]["number"].string {
    // Find the phone number
    print("The first telephone number of the first contact person:",number)
}
and Alamofire Combination
//Create URL objects
let url = URL(string:"http://www.hangge.com/getJsonData.php")!

Alamofire.request(url).validate().responseJSON { response in
    switch response.result.isSuccess {
    case true:
        if let value = response.result.value {
            let json = JSON(value)
            if let number = json[0]["phones"][0]["number"].string {
                // Find the phone number
                print("The first telephone number of the first contact person:",number)
            }
        }
    case false:
        print(response.result.error)
    }
}

2.1 Optional and Non-Optional Values

1. Optional getter

Selectable values are obtained by means of. number,. string,. bool,. int,. uInt,. float,. double,. array,. dictionary, int8, Uint8, int16, Uint16, int32, Uint32, int64, Uint64 and so on. We need to judge whether there is an alternative value or not, and we can get specific error information if it does not exist.

//int
if let age = json[0]["age"].int {
    print(age)
} else {
    //Print error message
    print(json[0]["age"])
}

//String
if let name = json[0]["name"].string {
    print(name)
} else {
    //Print error message
    print(json[0]["name"])
}

2. Non-optional getter

Use attributes like xxxValue to get values, and if not, return a default value. It saves us from judging how to unpack.

//If not a Number or nil, return 0
let age: Int = json[0]["age"].intValue

//If not a String or nil, return ""
let name: String = json[0]["name"].stringValue

//If not a Array or nil, return []
let list: Array<JSON> = json[0]["phones"].arrayValue

//If not a Dictionary or nil, return [:]
let phone: Dictionary<String, JSON> = json[0]["phones"][0].dictionaryValue

3. Raw object

let jsonObject = json.object as AnyObject

let jsonObject = json.rawValue  as AnyObject

//JSON Converts to Data
let data = json.rawData()

//JSON Converts to String Strings
if let string = json.rawString() {
    //Do something you want
}

//JSON is translated into Dictionary dictionary ([String: AnyObject]?)
if let dic = json.dictionaryObject {
    //Do something you want
}

//JSON is converted to an Array array ([AnyObject]?)
if let arr = json.arrayObject {
    //Do something you want
}

4. Setting values

json[0]["age"].int =  101
json[0]["name"].string =  "hangge.com"
json[0]["phones"].arrayObject = [["name":"Fixed line", "number":110],["name":"Mobile phone", "number":120]]

5. Subscript access

//Mode 1
let number = json[0]["phones"][0]["number"].stringValue

//Mode 2
let number = json[0,"phones",0,"number"].stringValue

//Mode 3
let keys:[JSONSubscriptType] = [0,"phones",0,"number"]
let number = json[keys].stringValue

6. Loop through all data in JSON objects

(1) If the JSON data is an array type (Array)

for (index,subJson):(String, JSON) in json {
    print("\(index): \(subJson)")
}

(2) If JSON data is Dictionary

for (key,subJson):(String, JSON) in json[0] {
    print("\(key): \(subJson)")
}

Reference:

https://github.com/alibaba/HandyJSON/blob/master/README_cn.md

http://www.hangge.com/blog/cache/detail_968.html

Topics: JSON PHP Mobile github