美文网首页
HandyJSON 解析框架如何在解析的时候过滤空字符串

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

作者: 90后的晨仔 | 来源:发表于2021-04-26 19:14 被阅读0次

今天遇到两个问题:
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)
        }
        

相关文章

网友评论

      本文标题:HandyJSON 解析框架如何在解析的时候过滤空字符串

      本文链接:https://www.haomeiwen.com/subject/ifunlltx.html