看到这篇文章,要知道这篇文章告诉你什么,就是对json的解析的一个解释,解析的代码去百度就可以了,OC的、安卓的、JS的等等都很多,但是对于swift语言的小白来说,资料就少之又少,包括一些看不懂的,这篇就是解释,要让小白看懂:

先上代码,这是最基本的获取json形式

let url = NSURL(string: "http://... ...")

let data = NSData(contentsOfURL: url!)

if data != nil {

let dict: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)) as! NSDictionary  //通过系统的方法来获取json,实际开发中会用到第三方库,如alamofire,为了给小白看(大神不看这篇),用最基本的。。这时取到的json数据是字典

print("得到json数据了")

print(dict)      //输出json数据

rst = dict.objectForKey("rst") as! Int          //通过key来获取值,经典的键值对形式key-value

ecd = dict.objectForKey("ecd") as! Int

看得懂最基本的json,那么实际运用中,我不会只对一个key来取value,如tableview的cell肯定是数组的形式呀,这时候小白已经翻阅了别人的代码看了多遍,仍然不知别人的cell数据从哪里获得,原因就是,一般的做法是将json对象转换为model存了起来,再从model对象去取,这一步转化让很多小白浪费了很多时间。

class consumerDetail: NSObject, DictModelProtocol {

var rst:Int = -1

var total:Int = -1

var rows:[Details]?

class func loadConsumerDetail(completion:(data: consumerDetail?, error: NSError?) -> Void) {

let url = NSURL(string: "http://183.252.21.19:81/bhys/d/api/?apiType=costDetail&rqsJson=%7B%22cardNo%22:%229999000002111%22%7D&sign=123456789")

let data = NSData(contentsOfURL: url!)

//        let path = NSBundle.mainBundle().pathForResource("Details", ofType: nil)   //这是一开始测试的时候用的本地json数据

//        let data = NSData(contentsOfFile: path!)

if data != nil {

let dict: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)) as! NSDictionary

let rspJson = dict.objectForKey("rspJson") as! NSDictionary

print("得到json数据了")

let modelTool = DictModelManager.sharedManager   //此处的DictModelManager是自定义转换类,类如下文

let data = modelTool.objectWithDictionary(rspJson, cls: consumerDetail.self) as? consumerDetail   //得到转换类的字典转对象方法将对象存起来,回调completion返回data数据就是对象,错误不做处理

completion(data: data, error: nil)

}

}

static func customClassMapping() -> [String : String]? {

return ["rows" : "\(Details.self)"]     //模型的配对

}

}

class Details:NSObject {    //模型,是不是和javabean很像,其实swift和java挺像的,个人觉得

var amount: String?

var orgName: String?

var occurTime: String?

var state:String?

}

下面是viewcontroller,取得data对象后,将其放入模型中,如下

private var detail: consumerDetail?

override func viewDidLoad() {

super.viewDidLoad()

self.title = "消费明细"

setTableView()

consumerDetail.loadConsumerDetail { (data, error) -> Void in

let tmpSelf = self

tmpSelf.detail = data

}

}

当cell获取时就可以轻松得到了

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = detailCellTableViewCell.cellWithTableView(tableView)

let goods = detail?.rows![indexPath.row]

cell.details = goods

print("得到cell")

return cell

}

//自定义转换类

public class DictModelManager {

private static let instance = DictModelManager()

// 全局public统一访问入口

public class var sharedManager: DictModelManager {

return instance

}

//  字典转模型

//  - parameter dict: 数据字典

//  - parameter cls:  模型类

//  - returns: 模型对象

public func objectWithDictionary(dict: NSDictionary, cls: AnyClass) -> AnyObject? {

let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String

// 模型信息

let infoDict = fullModelInfo(cls)

let obj: AnyObject = (cls as! NSObject.Type).init()

autoreleasepool {  // 3. 遍历字典对

iOSapp的json告示的更多相关文章

  1. 使用TSQL查询和更新 JSON 数据

    JSON是一个非常流行的,用于数据交换的文本数据(textual data)格式,主要用于Web和移动应用程序中.JSON 使用“键/值对”(Key:Value pair)存储数据,能够表示嵌套键值对 ...

  2. 【疯狂造轮子-iOS】JSON转Model系列之二

    [疯狂造轮子-iOS]JSON转Model系列之二 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇<[疯狂造轮子-iOS]JSON转Model系列之一> ...

  3. 【疯狂造轮子-iOS】JSON转Model系列之一

    [疯狂造轮子-iOS]JSON转Model系列之一 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 之前一直看别人的源码,虽然对自己提升比较大,但毕竟不是自己写的,很容易遗 ...

  4. Taurus.MVC 2.2 开源发布:WebAPI 功能增强(请求跨域及Json转换)

    背景: 1:有用户反馈了关于跨域请求的问题. 2:有用户反馈了参数获取的问题. 3:JsonHelper的增强. 在综合上面的条件下,有了2.2版本的更新,也因此写了此文. 开源地址: https:/ ...

  5. .NET Core系列 : 2 、project.json 这葫芦里卖的什么药

    .NET Core系列 : 1..NET Core 环境搭建和命令行CLI入门 介绍了.NET Core环境,本文介绍.NET Core中最重要的一个配置文件project.json的相关内容.我们可 ...

  6. 一个粗心的Bug,JSON格式不规范导致AJAX错误

    一.事件回放  今天工作时碰到了一个奇怪的问题,这个问题很早很早以前也碰到过,不过没想到过这么久了竟然又栽在这里. 当时正在联调一个项目,由于后端没有提供数据接口,于是我直接本地建立了一个 json ...

  7. JSON.parse()和JSON.stringify()

    1.parse 用于从一个字符串中解析出json 对象.例如 var str='{"name":"cpf","age":"23&q ...

  8. json与JavaScript对象互换

    1,json字符串转化为JavaScript对象: 方法:JSON.parse(string) eg:var account = '{"name":"jaytan&quo ...

  9. .NET平台开源项目速览(18)C#平台JSON实体类生成器JSON C# Class Generator

    去年,我在一篇文章用原始方法解析复杂字符串,json一定要用JsonMapper么?中介绍了简单的JSON解析的问题,那种方法在当时的环境是非常方便的,因为不需要生成实体类,结构很容易解析.但随着业务 ...

随机推荐

  1. python打怪之路【第二篇】:ImportError: No module named setuptools

    在python安装第三方模块时出现如下错误: python错误:ImportError: No module named setuptools这句错误提示的表面意思是:没有setuptools的模块, ...

  2. PHP 小方法之 算生日

    if (! function_exists ( 'diff_date' )) { function diff_date($date1, $date2){ $datestart = date ( 'Y- ...

  3. List怎么遍历删除元素

    public static void main(String[] args) {  List<String> list = new ArrayList<String>();   ...

  4. JQuery的概述

    一.什么是 jQuery 1.jQuery是一个JavaScript库,jQuery 极大地简化了 JavaScript 编程.它通过封装原生的JavaScript函数得到一整套定义好的方法. 2.它 ...

  5. 主页面获取iframe 的子页面方法。

    父页面parent.html <html> <head> <script type="text/javascript"> function sa ...

  6. Security » Authorization » 简单授权

    Simple Authorization¶ 简单授权 82 of 86 people found this helpful Authorization in MVC is controlled thr ...

  7. Linux Socket编程(不限Linux)

    "一切皆Socket!" 话虽些许夸张,但是事实也是,现在的网络编程几乎都是用的socket. --有感于实际编程和开源项目研究. 我们深谙信息交流的价值,那网络中进程之间如何通信 ...

  8. EaseType缓动函数

    http://sol.gfxile.net/interpolation/   一篇很详细的图文

  9. bzoj 3130: [Sdoi2013]费用流

    #include<cstdio> #include<iostream> #define M 10000 #define inf 0x7fffffff #include<c ...

  10. HDU 2871 Memory Control

    一共4种操作 其中用线段树 区间合并,来维护连续空的长度,和找出那个位置.其他用vector维护即可 #include<cstring> #include<cstdio> #i ...