今天遇到两个问题:
1.后台返回的json数据字段有时候过长,有时候名称带下划线,所以我想在解析的时候对其进行处理。
2.后台返回的json数据中对应的字段值偶尔会有空字符串,所以需要特殊处理一下。
-
第一个问题解决方案
-
在继承HandyJSON的model中实现以下方法
func mapping(mapper: HelpingMapper) {
mapper <<<
testStr <-- "stringImplicitlyUnwrapped"
}
-
第二个问题解决方案:在如下方法对有空字符串的字符串进行过滤处理。
func didFinishMapping() {
testStr = testStr.trimmingCharacters(in: .whitespaces)
}
-
下边的测试例子来源HandyJSON官方
class BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: String?
var testStr = ""
func mapping(mapper: HelpingMapper) {
mapper <<<
testStr <-- "stringImplicitlyUnwrapped"
}
func didFinishMapping() {
testStr = testStr.trimmingCharacters(in: .whitespaces)
}
required init() {}
}
-
测试调用的时候
let jsonString = "{\"doubleOptional\":\" ceshi\",\"stringImplicitlyUnwrapped\":\" hello\",\"int\":1}"
print(jsonString)
print("=========")
if let object = BasicTypes.deserialize(from: jsonString) {
print(object.int)
print(object.doubleOptional!)
print(object.testStr)
}
网友评论