HandyJSON 解析框架如何在解析的时候过滤空字符串

今天遇到两个问题:
1.后台返回的json数据字段有时候过长,有时候名称带下划线,所以我想在解析的时候对其进行处理。
2.后台返回的json数据中对应的字段值偶尔会有空字符串,所以需要特殊处理一下。

-** 第一个问题解决方案**

  • 在继承HandyJSON的model中实现以下方法
 func mapping(mapper: HelpingMapper) {
        mapper <<<
            testStr <--  "stringImplicitlyUnwrapped"
    }
复制代码
  • 第二个问题解决方案:在如下方法对有空字符串的字符串进行过滤处理。
  func didFinishMapping() {
        testStr =  testStr.trimmingCharacters(in: .whitespaces)
    }
 
复制代码
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)
        }
        
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享