Swift框架学习之-数据解析SwiftyJSON

原创 2017-06-07

SwiftyJSON数据解析框架,据ThoughtWorks的周教练说,是由他们中国区的一位同事开发的,在之前我们使用的是OC的解析框架,现在切换到Swift开发,下面就来说一说如何使用该框架。在学习使用之前,你大致需要了解框架如下图几个部分:

集成SwiftyJSON

你可以通过CocoaPods的Podfile来安装你的SwiftyJSON,要求你iOS deployment target 必须在8.0以上

platform :ios, '8.0'

target 'SwiftyJsonDemo' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!
    pod 'SwiftyJSON', '~>3.1.4'
end

用法:

初始化
import SwiftyJSON

这里先准备数据,在你的工程中加入一个文件SwiftyJSON.json文件,并将你的json字符串拷贝至文件(这里我们采用SwiftyJSON官方提供的示例数据)

var jsonData: Data?
if let file = Bundle.main.path(forResource: "SwiftyJSON", ofType: "json") {
    jsonData = try? Data(contentsOf: URL(fileURLWithPath: file))
} else {
    print("Fail")
}

let jsonObject = try JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments) as? [[String: AnyObject]]

let jsonString = String(data: jsonData!, encoding: .utf8)

从上述思维导图给出的,我们可以了解到SwiftyJSON提供了三种初始化JSON方式:

  • 直接通过数据:
let json = JSON(data: jsonData)
  • 通过object: Any初始化:这里需要注意的是参数object必须包含如下属性:NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull;而且这里的JsonString是框架是不会将它转换的你应该通过init(parseJson: String)方式处理,并且所有的dictionary 所包含的keys最好是NSString/String。
let json = JSON(jsonObject as Any)
  • 通过JsonString 初始化:
let json =JSON(parseJSON: jsonString)
通过下标访问

如有如下数据(随意举的一个例子):

[
      {
          "name": {"firstName": "f1", "lastName":"l1"},
          "address":"成都市xxx"
          "mainPage":"http://bit.ly/oauth-dancer",
          "age":23
      }, 
      {
          "name": {"firstName": "f2", "lastName":"l2"},
          "address":"北京市xxx"
          "mainPage":"http://bit.ly/oauth-dancer2",
          "age":25
      }
]
// 数组访问
let student: Dictionary? = json[0].dictionary
let student = json[0].dictionaryValue

// string
let address: String? = student["address"].string
let address = student["address"].stringValue

// int
let age: Int? = student["age"].int
let age = student["age"].intValue

...

从上述你可以看出,SwiftyJSON给我们提供的获取数据包含了Optional 与 Non-Optional两种方式,从源码可以看出各个数据类型各自对应的非可选类型返回的默认值:

fileprivate var rawArray: [Any] = []
fileprivate var rawDictionary: [String : Any] = [:]
fileprivate var rawString: String = ""
fileprivate var rawNumber: NSNumber = 0
fileprivate var rawNull: NSNull = NSNull()
fileprivate var rawBool: Bool = false

sub 访问:SwiftyJSON还提供了一个比较便捷的方式访问,比如你需要访问上述数据中第一个数据的firstName

// 常规方式
let firstName = json[0]["name"]["firstName"].stringValue
// path 访问方式
let firstName = json[0, "name", "first"].stringValue
遍历数据

遍历Dictionary :

for (key, subJSON) : (String, JSON) in json {
    print("key : \(key)   subJson-Type : \(subJSON?.type)")
}

遍历数组Array:

// 在这里需要注意的是:此时的index应该是 0..
通过字面量转换
//StringLiteralConvertible
let json: JSON = "I'm a json" 

//DictionaryLiteralConvertible
let json: JSON =  ["I":"am", "a":"json"]

//ArrayLiteralConvertible
let json: JSON =  ["I", "am", "a", "json"]

//Array & Dictionary
var json: JSON =  ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]]
json["list"][3]["what"] = "that"
json["list",3,"what"] = "that"

json["list",3,"what"] = "that"

...
错误处理

在现有版本3.x中通过Global Variables定义了:

///Error code
public let ErrorUnsupportedType: Int = 999
public let ErrorIndexOutOfBounds: Int = 900
public let ErrorWrongType: Int = 901
public let ErrorNotExist: Int = 500
public let ErrorInvalidJSON: Int = 490

根据Github上的介绍在4.x版本中使用的是SwiftyJSONError:

public enum SwiftyJSONError: Int, Swift.Error {
    case unsupportedType = 999
    case indexOutOfBounds = 900
    case elementTooDeep = 902
    case wrongType = 901
    case notExist = 500
    case invalidJSON = 490
}
其他处理方式
// 将JSON转换为rawData
if let data = json.rawData() {
}

// 将JSON转换为rawString
if let string = json.rawString() {
}

// 判定是否存在
if json["name"].exists() {
    print("exist")
}

SwiftyJSON的基础用法就介绍到这里,更多深入的用法可以到Github查阅,或者阅读源码查看。

你可能感兴趣的:(Swift框架学习之-数据解析SwiftyJSON)