swift 解析框架HandyJSON

swift 解析框架HandyJSON

本文demo都来源于HandyJSON,只研究使用方法,感兴趣的可以直接去HandyJSON看看。也可以看看这篇文章HandyJSON简单使用

1.普通使用

classBasicTypes:HandyJSON{varint:Int=2vardoubleOptional:Double?varstringImplicitlyUnwrapped:String!requiredinit(){}}//反序列化letjsonString="{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"ifletobject=BasicTypes.deserialize(from:jsonString){print(object.int)print(object.doubleOptional!)print(object.stringImplicitlyUnwrapped!)}print("===============")//序列化letobject=BasicTypes()object.int=1object.doubleOptional=1.1object.stringImplicitlyUnwrapped="hello"print(object.toJSON()!)// 序列化为字典print(object.toJSONString()!)// 序列化为json字符串print(object.toJSONString(prettyPrint:true)!)//序列化为json格式的字符串

2.JSON转数组转成model数组

classCat:HandyJSON{varname:String?varid:String?requiredinit(){}}letjsonArrayString:String?="[{\"name\":\"Bob\",\"id\":\"1\"}, {\"name\":\"Lily\",\"id\":\"2\"}, {\"name\":\"Lucy\",\"id\":\"3\"}]"ifletcats=[Cat].deserialize(from:jsonArrayString){cats.forEach({(cat)inprint(cat?.name!??"nil")})}

3.嵌套json解析

classBasicTypes:HandyJSON{varbool:Bool=truevarintOptional:Int?vardoubleImplicitlyUnwrapped:Double!varanyObjectOptional:Any?vararrayInt:Array=[]vararrayStringOptional:Array?varsetInt:Set?vardictAnyObject:Dictionary=[:]varnsNumber=2varnsString:NSString?requiredinit(){}}letobject=BasicTypes()object.intOptional=1object.doubleImplicitlyUnwrapped=1.1object.anyObjectOptional="StringValue"object.arrayInt=[1,2]object.arrayStringOptional=["a","b"]object.setInt=[1,2]object.dictAnyObject=["key1":1,"key2":"stringValue"]object.nsNumber=2object.nsString="nsStringValue"letjsonString=object.toJSONString()!iflettempObject=BasicTypes.deserialize(from:jsonString){print("arrayStringOptional==>\(tempObject.arrayStringOptional!)");}

4.自定义解析

classCat:HandyJSON{varid:Int64!varname:String!varparent:(String,String)?requiredinit(){}funcmapping(mapper:HelpingMapper){// 指定 id 字段用 "cat_id" 去解析mapper.specify(property:&id,name:"cat_id")// 指定 parent 字段用下边这个方法去解析//方法一:mapper.specify(property:&parent){(rawString)->(String,String)inletparentNames=rawString.split{$0=="/"}.map(String.init)return(parentNames[0],parentNames[1])/*方法二:

      let transformOf  = TransformOf<(String, String), String>(fromJSON: { (rawString) -> (String, String)? in

          if let parentNames = rawString?.split(separator: "/").map(String.init) {

              return (parentNames[0], parentNames[1])

          }

          return nil

      }, toJSON: { (tuple) -> String? in

          if let _tuple = tuple {

              return "\(_tuple.0)/\(_tuple.1)"

          }

          return nil

      })


        mapper.specify(property: &parent) { (tt) -> (String,String) in

            transformOf.transformFromJSON(tt)!

        }*/}}}letjsonString="{\"cat_id\":12345,\"name\":\"Kitty\",\"parent\":\"Tom/Lily\",\"friend\":{\"id\":54321,\"name\":\"Lily\"}}"ifletcat=Cat.deserialize(from:jsonString){print(cat.id??"")print(cat.parent??"")}

你可能感兴趣的:(swift 解析框架HandyJSON)