import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
JsonGPL()
}
func JsonGPL()
{
//Json对象
let user:[String: Any] = [
"uname": "张三",
"tel": ["mobile": "138", "home": "010"]
]
//判断是否JSon格式
if !JSONSerialization.isValidJSONObject(user) {
print("is not a valid json object")
}
//利用自带的json库转换成Data
//设置options为JSONSerialization.WritingOptions.prettyPrinted,则打印格式更好阅读
let data = try? JSONSerialization.data(withJSONObject: user, options: .prettyPrinted)
let Jsonstr = String(data: data!, encoding: .utf8)
print("Jsonstr============\(Jsonstr)")
//Data转换JSON
let Json2 = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
print("Json2=============\(Json2)")
if !JSONSerialization.isValidJSONObject(Json2) {
print("Json2 is not a valid json object")
}
//验证JSON对象可用性
let uname = Json2?["uname"]
let mobile = (Json2?["tel"] as! [String: Any])["mobile"]
print("get Json Object:","uname: \(uname), mobile: \(mobile)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
网友评论