Swift开发:使用SwiftyJSON解析JSON数据

前端之家收集整理的这篇文章主要介绍了Swift开发:使用SwiftyJSON解析JSON数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1 下载配置SwiftyJSON

GitHub地址:https://github.com/SwiftyJSON/SwiftyJSON

使用配置:直接将 SwiftyJSON.swift添加到项目中即


2 解析案例文件

demo.json 放置项目中,json内容如下

{
	"system":	{
		"id":	754717486,"model":	"32C","max":	32,"max_out":	32,"run":	"Run 003:00:31","temp":	"20~35","wcolor":	"#66ff00","temp_war":	false,"mark":	1766,"ahpd":	1,"uhpd":	1,"cont":	1,"ip":	"192.168.88.229","port":	1001,"update":	true,"lang":	0
	},"info":	{
		"Sync":	false,"port":	[{
				"io":	1,"pow":	0,"SName":	"SYSTEM VGA\n ","type":	2,"power":	1,"vsw":	7,"Iasw":	7,"Easw":	7,"usw":	0,"flag":	false,"hpd":	"HPD OFF","res":	"Power off","vsd":	"N/A","v_hdcp":	"N/A","vmode":	1,"vaudio":	1,"vhdcp":	1,"EName":	"SYSTEM EDID\n"
			},{
				"io":	0,"pow":	1,"SName":	"SYSTEM EDID\n"
			},"SName":	"SHARP HDMI\n "
			},"SName":	"U28D590\n    "
			},{
				"io":	1,"SName":	"Skyworth UHD","type":	12,"res":	"NoSignal","vaudio":	0,"vhdcp":	0,"SName":	"LG TV\n      "
			},"SName":	"SYSTEM EDID\n","type":	1,{
				"io":	2,"pow":	2,"type":	4,"res":	"Auto off","EName":	"NULL\r"
			},"pow":	1
			},"EName":	"43PUF6056/T3"
			},"type":	134,"EName":	"U28E590\n    ","s_res":	1,"s_out":	0,"s_arrt":	0,"s_brightness":	50,"s_contrast":	50,"s_saturability":	50,"s_sharpness":	50,"s_rv":	0,"s_gv":	0,"s_bv":	0
			},"pow":	1
			}]
	}
}

3 开始解析

只有部分解析,其他解析结合demo.json就知道怎么解析了

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.
        
        let path = Bundle.main.path(forResource: "demo",ofType: "json");
        
        let jsonData = NSData(contentsOfFile: path!);
        
        do{
            
            let json = try JSON(data: jsonData! as Data);
            
            //system
            let system_array = json["system"];
            print("id: \((system_array["id"].int)!)");
            print("model: \((system_array["model"].string)!)");
            
            //info
            let info_array = json["info"];
            
            // info sync
            print("sync: \((info_array["Sync"].bool)!)");
            
            
            //info port
            let info_port_array = info_array["port"];
            
            for i in 0..<info_port_array.count {
                let io = info_port_array[i]["io"].int!;
                print("io:\(io)");
            }
            
        }
        catch{
            print("error ");
        }
    }

4 效果

原文链接:https://www.f2er.com/swift/321051.html

猜你在找的Swift相关文章