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)
        }
        
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。