iOS开发之网络数据解析(一)--JSON解析简介
摘要: 前言:对服务器请求之后,返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除外) 本篇随便先讲解JSON解析。 正文: 关于JSON: JSON是一种轻量级的数据格式,一般用于数据交互 JSON的格式很像Objective-C中的字典和数组:{"name":"jack","age":10} 补充: 标准的JSON格式的注意点:key必须用双引号。
关于JSON:
1 JSON是一种轻量级的数据格式,一般用于数据交互
2 JSON的格式很像Objective-C中的字典和数组:{"name":"jack","age":10}
补充:
标准的JSON格式的注意点:key必须用双引号。(但是在Java中是单引号)
其中:null--返回OC里的NSNull类型
students.tst
{"name":"BeJson","url":"http://www.bejson.com","page":88,"isNonProfit":true,"address":{"street":"科技园路.","city":"江苏苏州","country":"中国"}}
建立继NSObject的Infor文件
import UIKit
class Infor: NSObject {
var isNonProfit:Int? = nil
var name:String? = nil
var page:Int? = nil
var url:String? = nil
var address:Address? = nil
}
class Address:NSObject{
var city:String? = nil
var country:String? = nil
var street:String? = nil
}
//
// ViewController.swift
// Json
//
// Created by 。。。 on 2017/5/16.
// Copyright © 2017年 m. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//先把json读取进来
let path = Bundle.main.path(forResource: "students", ofType: "tst")
//let url = URL(fileURLWithPath: path)
let url = URL(fileURLWithPath: path!)
let data = try! Data(contentsOf: url)
let dic = try!
JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:NSObject]
//print(dic)
//简析成对象
let infor = Infor()
infor.name = dic["name"] as? String
infor.isNonProfit = dic["isNonProfit"]as?Int
infor.page = dic ["page"]as?Int
infor.url = dic ["url"]as?String
let cityDic = dic["address"] as?[String:String]
let address = Address()
address.city = cityDic?["city"]
address.country = cityDic?["country"]
address.street = cityDic?["street"]
infor.address = address
print(infor.address?.city )
}
}