Jasoom 是一个使用方便,类型安全 的NSJSONSerialization Swift 封装器。
JSON 解析:
do { let json = try JSON.parseData(data) if json["name"].isUndefined { throw .MissingName } if json["info"]["age"].isUndefined { throw .MissingAge } let model = MyModel( name: json["name"].stringValue! age: json["info"]["age"].intValue! married: json["status"]["married"].boolValue ?? false firstCar: json["cars"][0].stringValue ?? "" ) } catch { // Handle error }
JSON 生成:
var object = JSON.object() object["name"] = .String("Bob Smith") object["info"] = JSON.object() object["info"]["age"] = .Number(10) object["status"] = JSON.object() object["status"]["married"] = .Number(true) object["cars"] = JSON.array() object["cars"].append(.String("Ford Mustang")) do { let data = try object.generateData() } catch { // Handle error }