IOS

使用Just实现网络数据的获取与解析

2019-01-11  本文已影响0人  瑟闻风倾

1. 网络Json数据为:

{
  "code": "0",
  "msg": "success",
  "res": {
    "machineList": [
      {
        "cm_id": "319",
        "company_id": "50",
        "machine_id": "32",
        "cate": {
          "cate_id": "102",
          "sort": "0",
          "parent_id": "2",
          "cate_name": "MA04自动连续锁眼机",
          "image": "/upload/image/2018/09/60d9f57d939c310894db9f819128e36c.jpg",
          "machine_num": "0",
          "unit": "个",
          "time_unit": "秒",
          "is_jtj": "0",
          "tiered_num": "0",
          "tiered_discount": "0.00"
        },
        "cust_group": "10",
        "is_lock": "0",
        "is_rent": "0",
        "status": "1",
        "machine": {
          "machine_id": "32",
          "cate": "2",
          "cate2": "102",
          "name": "问题测试  ",
          "sn": "Qtest",
          "channel": "1",
          "price": "0.000",
          "description": null,
          "image": "http://s.uchat.com.cn/upload/image/2018/09/60d9f57d939c310894db9f819128e36c_150x150.jpg",
          "tags": null,
          "protocol": null,
          "location": "",
          "device_id": "39590889",
          "imsi": null,
          "ProductKey": null,
          "DeviceName": null,
          "DeviceSecret": null,
          "IotId": null,
          "lac": "22706",
          "ci": "48888",
          "csq": "0",
          "lat": "",
          "lng": "",
          "software": null,
          "build_time": "0",
          "hardware": null,
          "ota_time": "0",
          "add_time": "1534904725",
          "rent_out": "1",
          "status": "0",
          "status_time": "1535339005",
          "login_type": "7",
          "maintain_time": "0",
          "last_time": "0",
          "params": null,
          "param_time": "0",
          "parameter": null,
          "params_set": "{\"\":null}",
          "devctrl": "1",
          "sale_type": "2",
          "is_del": "0"
        },
        "use_time": 0,
        "i": 1
      },
      {
        "cm_id": "318",
        "company_id": "50",
        "machine_id": "33",
        "cate": "0",
        "cust_group": "10",
        "is_lock": "0",
        "is_rent": "0",
        "status": "1",
        "machine": {
          "machine_id": "33",
          "cate": "2",
          "cate2": "0",
          "name": "迈卡袖衩机",
          "sn": "0109",
          "channel": "1",
          "price": "0.300",
          "description": null,
          "image": "http://s.uchat.com.cn/public/images/nopic300.png",
          "tags": null,
          "protocol": null,
          "location": "",
          "device_id": "39597199",
          "imsi": null,
          "ProductKey": null,
          "DeviceName": null,
          "DeviceSecret": null,
          "IotId": null,
          "lac": "0",
          "ci": "0",
          "csq": "0",
          "lat": "",
          "lng": "",
          "software": null,
          "build_time": "0",
          "hardware": null,
          "ota_time": "0",
          "add_time": "1534917235",
          "rent_out": "1",
          "status": "0",
          "status_time": null,
          "login_type": "7",
          "maintain_time": "0",
          "last_time": "0",
          "params": null,
          "param_time": "0",
          "parameter": null,
          "params_set": "{\"\":null}",
          "devctrl": "1",
          "sale_type": "2",
          "is_del": "0"
        },
        "use_time": 0,
        "i": 2
      },
      {
        "cm_id": "306",
        "company_id": "50",
        "machine_id": "25",
        "cate": "0",
        "cust_group": "0",
        "is_lock": "0",
        "is_rent": "1",
        "status": "1",
        "machine": {
          "machine_id": "25",
          "cate": "2",
          "cate2": "0",
          "name": "开发测试(agent)",
          "sn": "LHCS02",
          "channel": "1",
          "price": "0.000",
          "description": null,
          "image": "http://s.uchat.com.cn/public/images/nopic300.png",
          "tags": null,
          "protocol": null,
          "location": "",
          "device_id": "38785262",
          "imsi": "460040148224239",
          "ProductKey": null,
          "DeviceName": null,
          "DeviceSecret": null,
          "IotId": null,
          "lac": "22706",
          "ci": "48888",
          "csq": "12",
          "lat": "",
          "lng": "",
          "software": "macia_datacollector_v2.0.0",
          "build_time": "0",
          "hardware": "Protocol_Converter_v3.5",
          "ota_time": "0",
          "add_time": "1533892588",
          "rent_out": "1",
          "status": "0",
          "status_time": "1545917649",
          "login_type": "7",
          "maintain_time": "0",
          "last_time": "0",
          "params": null,
          "param_time": "0",
          "parameter": null,
          "params_set": "{\"\":null}",
          "devctrl": "1",
          "sale_type": "1",
          "is_del": "0"
        },
        "use_time": 0,
        "i": 3
      },
      {
        "cm_id": "189",
        "company_id": "50",
        "machine_id": "142",
        "cate": {
          "cate_id": "106",
          "sort": "0",
          "parent_id": "2",
          "cate_name": "MCD门襟卷缝机",
          "image": "/upload/image/2018/09/09e8b04e355df957610c6e33d81275de.jpg",
          "machine_num": "0",
          "unit": "个",
          "time_unit": "秒",
          "is_jtj": "0",
          "tiered_num": "0",
          "tiered_discount": "0.00"
        },
        "cust_group": "0",
        "is_lock": "0",
        "is_rent": "0",
        "status": "1",
        "machine": {
          "machine_id": "142",
          "cate": "2",
          "cate2": "106",
          "name": "门襟卷缝机(一楼测试2)",
          "sn": "MCD201793",
          "channel": "1",
          "price": "0.000",
          "description": null,
          "image": "http://s.uchat.com.cn/upload/image/2018/09/09e8b04e355df957610c6e33d81275de_150x150.jpg",
          "tags": null,
          "protocol": null,
          "location": "",
          "device_id": "505776789",
          "imsi": "460040148225988",
          "ProductKey": null,
          "DeviceName": null,
          "DeviceSecret": null,
          "IotId": null,
          "lac": "26475",
          "ci": "12266",
          "csq": "0",
          "lat": "",
          "lng": "",
          "software": "macia_datacollector_v2.0.0",
          "build_time": "0",
          "hardware": "Protocol_Converter_v3.5",
          "ota_time": "0",
          "add_time": "1544418000",
          "rent_out": "1",
          "status": "0",
          "status_time": "1546847997",
          "login_type": "7",
          "maintain_time": "1000",
          "last_time": "0",
          "params": null,
          "param_time": "0",
          "parameter": null,
          "params_set": null,
          "devctrl": "0",
          "sale_type": "2",
          "is_del": "0"
        },
        "use_time": 0,
        "i": 4
      }
    ],
    "machineNum": 4,
    "machineGroup": [
      {
        "group_id": "10",
        "name": "包缝机"
      }
    ],
    "onlineNum": 0,
    "company_id": 50
  }
}

2. 数据模型

备注: 网络JSON数据转换为Swift数据模型,参考JSON文件自动生成Swift模型文件
(1)RootClass.swift

//
//  RootClass.swift
//
//  Create by 云 徐 on 3/1/2019
//  Copyright © 2019. All rights reserved.
//  模型生成器(小波汉化)JSONExport: https://github.com/Ahmed-Ali/JSONExport

import Foundation

//1. API操作成功与否的对象
struct RootClass{

    var code : String!
    var msg : String!
    var res : Re!


    /**
     * 用字典来初始化一个实例并设置各个属性值
     */
    init(fromDictionary dictionary: NSDictionary){
        code = dictionary["code"] as? String
        msg = dictionary["msg"] as? String
        if let resData = dictionary["res"] as? NSDictionary{
                res = Re(fromDictionary: resData)
            }
    }

    /**
     * 把所有属性值存到一个NSDictionary对象,键是相应的属性名。
     */
    func toDictionary() -> NSDictionary
    {
        var dictionary = NSMutableDictionary()
        if code != nil{
            dictionary["code"] = code
        }
        if msg != nil{
            dictionary["msg"] = msg
        }
        if res != nil{
            dictionary["res"] = res.toDictionary()
        }
        return dictionary
    }

}

(2)Re.swift

//
//  Re.swift
//
//  Create by 云 徐 on 3/1/2019
//  Copyright © 2019. All rights reserved.
//  模型生成器(小波汉化)JSONExport: https://github.com/Ahmed-Ali/JSONExport

import Foundation

//2. API操作成功后的有效数据
struct Re{

    var companyId : Int!
    var machineGroup : [AnyObject]!
    var machineList : [MachineList]!
    var machineNum : Int!
    var onlineNum : Int!


    /**
     * 用字典来初始化一个实例并设置各个属性值
     */
    init(fromDictionary dictionary: NSDictionary){
        companyId = dictionary["company_id"] as? Int
        machineGroup = dictionary["machineGroup"] as? [AnyObject]
        machineList = [MachineList]()
        if let machineListArray = dictionary["machineList"] as? [NSDictionary]{
            for dic in machineListArray{
                let value = MachineList(fromDictionary: dic)
                machineList.append(value)
            }
        }
        machineNum = dictionary["machineNum"] as? Int
        onlineNum = dictionary["onlineNum"] as? Int
    }

    /**
     * 把所有属性值存到一个NSDictionary对象,键是相应的属性名。
     */
    func toDictionary() -> NSDictionary
    {
        var dictionary = NSMutableDictionary()
        if companyId != nil{
            dictionary["company_id"] = companyId
        }
        if machineGroup != nil{
            dictionary["machineGroup"] = machineGroup
        }
        if machineList != nil{
            var dictionaryElements = [NSDictionary]()
            for machineListElement in machineList {
                dictionaryElements.append(machineListElement.toDictionary())
            }
            dictionary["machineList"] = dictionaryElements
        }
        if machineNum != nil{
            dictionary["machineNum"] = machineNum
        }
        if onlineNum != nil{
            dictionary["onlineNum"] = onlineNum
        }
        return dictionary
    }

}

(3)RootClass.swift

//
//  MachineList.swift
//
//  Create by 云 徐 on 3/1/2019
//  Copyright © 2019. All rights reserved.
//  模型生成器(小波汉化)JSONExport: https://github.com/Ahmed-Ali/JSONExport

import Foundation

//3. 机器列表数据
struct MachineList{

    var cate : String!
    var cmId : String!
    var companyId : String!
    var custGroup : String!
    var i : Int!
    var isLock : String!
    var isRent : String!
    var machine : Machine!
    var machineId : String!
    var status : String!
    var useTime : Int!


    /**
     * 用字典来初始化一个实例并设置各个属性值
     */
    init(fromDictionary dictionary: NSDictionary){
        cate = dictionary["cate"] as? String
        cmId = dictionary["cm_id"] as? String
        companyId = dictionary["company_id"] as? String
        custGroup = dictionary["cust_group"] as? String
        i = dictionary["i"] as? Int
        isLock = dictionary["is_lock"] as? String
        isRent = dictionary["is_rent"] as? String
        if let machineData = dictionary["machine"] as? NSDictionary{
                machine = Machine(fromDictionary: machineData)
            }
        machineId = dictionary["machine_id"] as? String
        status = dictionary["status"] as? String
        useTime = dictionary["use_time"] as? Int
    }

    /**
     * 把所有属性值存到一个NSDictionary对象,键是相应的属性名。
     */
    func toDictionary() -> NSDictionary
    {
        var dictionary = NSMutableDictionary()
        if cate != nil{
            dictionary["cate"] = cate
        }
        if cmId != nil{
            dictionary["cm_id"] = cmId
        }
        if companyId != nil{
            dictionary["company_id"] = companyId
        }
        if custGroup != nil{
            dictionary["cust_group"] = custGroup
        }
        if i != nil{
            dictionary["i"] = i
        }
        if isLock != nil{
            dictionary["is_lock"] = isLock
        }
        if isRent != nil{
            dictionary["is_rent"] = isRent
        }
        if machine != nil{
            dictionary["machine"] = machine.toDictionary()
        }
        if machineId != nil{
            dictionary["machine_id"] = machineId
        }
        if status != nil{
            dictionary["status"] = status
        }
        if useTime != nil{
            dictionary["use_time"] = useTime
        }
        return dictionary
    }

}

(4)RootClass.swift

//
//  Machine.swift
//
//  Create by 云 徐 on 3/1/2019
//  Copyright © 2019. All rights reserved.
//  模型生成器(小波汉化)JSONExport: https://github.com/Ahmed-Ali/JSONExport

import Foundation

// 4. 机器数据模型
struct Machine{

    var deviceName : AnyObject!
    var deviceSecret : AnyObject!
    var iotId : AnyObject!
    var productKey : AnyObject!
    var addTime : String!
    var buildTime : String!
    var cate : String!
    var cate2 : String!
    var channel : String!
    var ci : String!
    var csq : String!
    var descriptionField : AnyObject!
    var devctrl : String!
    var deviceId : String!
    var hardware : String!
    var image : String!
    var imsi : String!
    var isDel : String!
    var lac : String!
    var lastTime : String!
    var lat : String!
    var lng : String!
    var location : String!
    var loginType : String!
    var machineId : String!
    var maintainTime : String!
    var name : String!
    var otaTime : String!
    var paramTime : String!
    var parameter : AnyObject!
    var params : AnyObject!
    var paramsSet : AnyObject!
    var price : String!
    //var protocol : AnyObject!
    var rentOut : String!
    var saleType : String!
    var sn : String!
    var software : String!
    var status : String!
    var statusTime : String!
    var tags : AnyObject!


    /**
     * 用字典来初始化一个实例并设置各个属性值
     */
    init(fromDictionary dictionary: NSDictionary){
        deviceName = dictionary["DeviceName"] as? AnyObject
        deviceSecret = dictionary["DeviceSecret"] as? AnyObject
        iotId = dictionary["IotId"] as? AnyObject
        productKey = dictionary["ProductKey"] as? AnyObject
        addTime = dictionary["add_time"] as? String
        buildTime = dictionary["build_time"] as? String
        cate = dictionary["cate"] as? String
        cate2 = dictionary["cate2"] as? String
        channel = dictionary["channel"] as? String
        ci = dictionary["ci"] as? String
        csq = dictionary["csq"] as? String
        descriptionField = dictionary["description"] as? AnyObject
        devctrl = dictionary["devctrl"] as? String
        deviceId = dictionary["device_id"] as? String
        hardware = dictionary["hardware"] as? String
        image = dictionary["image"] as? String
        imsi = dictionary["imsi"] as? String
        isDel = dictionary["is_del"] as? String
        lac = dictionary["lac"] as? String
        lastTime = dictionary["last_time"] as? String
        lat = dictionary["lat"] as? String
        lng = dictionary["lng"] as? String
        location = dictionary["location"] as? String
        loginType = dictionary["login_type"] as? String
        machineId = dictionary["machine_id"] as? String
        maintainTime = dictionary["maintain_time"] as? String
        name = dictionary["name"] as? String
        otaTime = dictionary["ota_time"] as? String
        paramTime = dictionary["param_time"] as? String
        parameter = dictionary["parameter"] as? AnyObject
        params = dictionary["params"] as? AnyObject
        paramsSet = dictionary["params_set"] as? AnyObject
        price = dictionary["price"] as? String
        //protocol = dictionary["protocol"] as? AnyObject
        rentOut = dictionary["rent_out"] as? String
        saleType = dictionary["sale_type"] as? String
        sn = dictionary["sn"] as? String
        software = dictionary["software"] as? String
        status = dictionary["status"] as? String
        statusTime = dictionary["status_time"] as? String
        tags = dictionary["tags"] as? AnyObject
    }

    /**
     * 把所有属性值存到一个NSDictionary对象,键是相应的属性名。
     */
    func toDictionary() -> NSDictionary
    {
        var dictionary = NSMutableDictionary()
        if deviceName != nil{
            dictionary["DeviceName"] = deviceName
        }
        if deviceSecret != nil{
            dictionary["DeviceSecret"] = deviceSecret
        }
        if iotId != nil{
            dictionary["IotId"] = iotId
        }
        if productKey != nil{
            dictionary["ProductKey"] = productKey
        }
        if addTime != nil{
            dictionary["add_time"] = addTime
        }
        if buildTime != nil{
            dictionary["build_time"] = buildTime
        }
        if cate != nil{
            dictionary["cate"] = cate
        }
        if cate2 != nil{
            dictionary["cate2"] = cate2
        }
        if channel != nil{
            dictionary["channel"] = channel
        }
        if ci != nil{
            dictionary["ci"] = ci
        }
        if csq != nil{
            dictionary["csq"] = csq
        }
        if descriptionField != nil{
            dictionary["description"] = descriptionField
        }
        if devctrl != nil{
            dictionary["devctrl"] = devctrl
        }
        if deviceId != nil{
            dictionary["device_id"] = deviceId
        }
        if hardware != nil{
            dictionary["hardware"] = hardware
        }
        if image != nil{
            dictionary["image"] = image
        }
        if imsi != nil{
            dictionary["imsi"] = imsi
        }
        if isDel != nil{
            dictionary["is_del"] = isDel
        }
        if lac != nil{
            dictionary["lac"] = lac
        }
        if lastTime != nil{
            dictionary["last_time"] = lastTime
        }
        if lat != nil{
            dictionary["lat"] = lat
        }
        if lng != nil{
            dictionary["lng"] = lng
        }
        if location != nil{
            dictionary["location"] = location
        }
        if loginType != nil{
            dictionary["login_type"] = loginType
        }
        if machineId != nil{
            dictionary["machine_id"] = machineId
        }
        if maintainTime != nil{
            dictionary["maintain_time"] = maintainTime
        }
        if name != nil{
            dictionary["name"] = name
        }
        if otaTime != nil{
            dictionary["ota_time"] = otaTime
        }
        if paramTime != nil{
            dictionary["param_time"] = paramTime
        }
        if parameter != nil{
            dictionary["parameter"] = parameter
        }
        if params != nil{
            dictionary["params"] = params
        }
        if paramsSet != nil{
            dictionary["params_set"] = paramsSet
        }
        if price != nil{
            dictionary["price"] = price
        }
//        if protocol != nil{
//            dictionary["protocol"] = protocol
//        }
        if rentOut != nil{
            dictionary["rent_out"] = rentOut
        }
        if saleType != nil{
            dictionary["sale_type"] = saleType
        }
        if sn != nil{
            dictionary["sn"] = sn
        }
        if software != nil{
            dictionary["software"] = software
        }
        if status != nil{
            dictionary["status"] = status
        }
        if statusTime != nil{
            dictionary["status_time"] = statusTime
        }
        if tags != nil{
            dictionary["tags"] = tags
        }
        return dictionary
    }

}

3. 数据获取与解析

注意:当然也可不用建立数据模型,没有数据模型时数据获取与解析可参考使用Alamofire与SwiftyJSON框架实现网络数据的获取与处理

import Just

var devices:[Device] = []
func getListByJust() {
         let paras = ["userId":"128","companyId":"50"]
         Just.post("https://api.uchat.com.cn/test/app", params: paras) { (r) in
            guard let json = r.json as? NSDictionary else{
                print("返回")
                return
            }
            
            //let res = RootClass(fromDictionary: json).res!
            let machineList = RootClass(fromDictionary: json).res.machineList!
            //数组转换:map方法接受一个闭包作为参数, 然后它会遍历整个数组,并对数组中每一个元素执行闭包中定义的操作,相当于对数组中的所有元素做了一个映射.
            self.devices = machineList.map{ (machi) -> Device in
                return Device(deviceId: machi.machine.sn, deviceName: machi.machine.name, deviceStatus: machi.machine.status, deviceCount: "", deviceImage: machi.machine.image, date: machi.machine.addTime)
            }
            dump(self.devices)//打印
        }
        
    }
struct Device:Codable {
    var deviceId:String
    var deviceName:String
    var deviceStatus:String
    var deviceCount:String
    var deviceImage:String
    var date:String
}
上一篇 下一篇

猜你喜欢

热点阅读