JSONSerialization解析JSON數(shù)據(jù)

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庫轉(zhuǎn)換成Data
        //設(shè)置options為JSONSerialization.WritingOptions.prettyPrinted,則打印格式更好閱讀
        let data = try? JSONSerialization.data(withJSONObject: user, options: .prettyPrinted)
        let Jsonstr = String(data: data!, encoding: .utf8)
        print("Jsonstr============\(Jsonstr)")
        //Data轉(zhuǎn)換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.
    }


}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容