GitHub链接:
https://github.com/mozhenhau/D3Json
D3Json
通过swift的反射特性,把json数据转换为model对象,本类最主要是解决了其他一般json转换类不能转换自定义对象的问题
只有一个文件:D3Json.swfit
扩展写在addExtension。可以参照扩展
Usage
例子在D3Json的Project里面,写了两个测试,一个是json转单model,一个是转model的list
在playgroud里面也有两个例子,但是playgroud里面,alloc自己定义的model时直接出错,可能是playgroud的bug
只需要一句代码:
var user:User = D3Json.jsonToModel(json, objc: User())就可以把json数据转换成User类
转成list对象:
var user:Array = D3Json.jsonToModelList(jsons, objc:User())就可以把json数据转换成Array类
Problem
- 不处理optional类型,建议写model类时先初始化
- 因为swift的反射reflect的缺陷,父类的属性不能转换
Requirements
- iOS 7.0+ / Mac OS X 10.9+
- Xcode 6.1
- Integration
- CocoaPods (iOS 8+, OS X 10.9+)
2.model对象转回Json
let data : NSData! = try? NSJSONSerialization.dataWithJSONObject(user, options: [])
model对象转Json,使用自带的NSJSONSerialization:
转载地址:http://www.hangge.com/blog/cache/detail_647.html
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label:UILabel = UILabel(frame:CGRectMake(100, 100,300,100));
label.text = "输出结果在控制台"
self.view.addSubview(label)
//测试结果在output终端输入,也可以建个命令行应用测试就可以了
testJson()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//测试json
func testJson() {
//Swift对象
let user = [
"uname": "张三",
"tel": ["mobile": "138", "home": "010"]
]
//首先判断能不能转换
if (!NSJSONSerialization.isValidJSONObject(user)) {
print("is not a valid json object")
return
}
//利用OC的json库转换成OC的NSData,
//如果设置options为NSJSONWritingOptions.PrettyPrinted,则打印格式更好阅读
let data : NSData! = try? NSJSONSerialization.dataWithJSONObject(user, options: [])
//NSData转换成NSString打印输出
let str = NSString(data:data, encoding: NSUTF8StringEncoding)
//输出json字符串
print("Json Str:"); print(str)
//把NSData对象转换回JSON对象
let json : AnyObject! = try? NSJSONSerialization
.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments)
print("Json Object:"); print(json)
//验证JSON对象可用性
let uname : AnyObject = json.objectForKey("uname")!
let mobile : AnyObject = json.objectForKey("tel")!.objectForKey("mobile")!
print("get Json Object:"); print("uname: (uname), mobile: (mobile)")
}
}
3.解析json字符串
(由于是字符串内容是json数组,则转成NSArray。如果字符串是json对象,则转成NSDictionary。)
let string: NSString = "[{"ID":1,"Name":"元台禅寺","LineID":1},{"ID":2,"Name":"田坞里山塘","LineID":1},{"ID":3,"Name":"滴水石","LineID":1}]"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
let jsonArr = try! NSJSONSerialization.JSONObjectWithData(data!,
options: NSJSONReadingOptions.MutableContainers) as! NSArray
print("记录数:(jsonArr.count)")
for json in jsonArr {
print("ID:", json.objectForKey("ID")!, " Name:", json.objectForKey("Name")!)
}