2017-04-25 178 views
-3

我想解析从服务器接收到的JSON数据。Swift JSON解析到数组

这是我的代码:

Alamofire.request(url).responseJSON { response in 
    let resCode = String(data: response.data!, encoding:String.Encoding.utf8) as String! 
    print("res:\(String(describing: resCode))") 
    //print("data:\(response.data!)") 
    let data = resCode?.data(using: String.Encoding.utf8) 
} 

打印清晰度:

RES:可选( “{\” 码\ ​​“:200,\” 数据\ “:{\” HDL \ “:[\” 81 \ “\ ”87 \“,\ ”65 \“,\ ”72 \“,\ ”81 \“,\ ”51.23288 \“],\ ”LDL \“:[\” 128 \ “\ ”107 \“,\ ”150 \“,\ ”116 \“,\ ”168 \“ \ ”114.03974 \“],\ ”三\“:[\ ”189 \“,\” 187 \ “\ ”210 \“,\ ”192 \“,\ ”200 \“ \ ”171.26027 \“],\ ”栏\“:[\ ”218 \“,\ ”203 \“,\” 225 \ “\ ”213 \“,\ ”280 \“ \ ”194.59934 \“],\ ”BMI \“:[\ ”21.8 \“,\ ”21.8 \“,\ ”21.5 \“,\” 21.8 \ “\ ”22.1 \“,\ ”25.28467 \“] \ ”年度\“:\ ”2011-04-20 \“,\ ”2012-04-03 \“,\” 2013年6月13日\ “\ ”2014年5月26日\“ \ ”2016年6月8日\“,\ ”预测\“]}}” )

我想将每个数据存储在HDL,LDL,TRI,COL,BMI和YEAR数组中。

回答

1

您需要使用JSONSerialization方法的JSONObject(附:数据)的JSON数据转换为词典:

let json = "{\"code\":200,\"data\":{\"hdl\":[\"81\",\"87\",\"65\",\"72\",\"81\",\"51.23288\"],\"ldl\":[\"128\",\"107\",\"150\",\"116\",\"168\",\"114.03974\"],\"tri\":[\"189\",\"187\",\"210\",\"192\",\"200\",\"171.26027\"],\"col\":[\"218\",\"203\",\"225\",\"213\",\"280\",\"194.59934\"],\"bmi\":[\"21.8\",\"21.8\",\"21.5\",\"21.8\",\"22.1\",\"25.28467\"],\"year\":[\"2011-04-20\",\"2012-04-03\",\"2013-06-13\",\"2014-05-26\",\"2016-06-08\",\"predict\"]}}" 
let data = Data(json.utf8) 

if let dict = (try? JSONSerialization.jsonObject(with: data)) as? [String:Any], 
    let subdict = dict["data"] as? [String:[String]] { 
    let hdl = subdict["hdl"] // ["81", "87", "65", "72", "81", "51.23288"] 
    let ldl = subdict["ldl"] // ["128", "107", "150", "116", "168", "114.03974"] 
    let tri = subdict["tri"] // ["189", "187", "210", "192", "200", "171.26027"] 
    let col = subdict["col"] // ["218", "203", "225", "213", "280", "194.59934"] 
    let bmi = subdict["bmi"] // ["21.8", "21.8", "21.5", "21.8", "22.1", "25.28467"] 
    let year = subdict["year"] // ["2011-04-20", "2012-04-03", "2013-06-13", "2014-05-26", "2016-06-08", "predict"] 
}