这里假设有一大串字符串,格式是json字典格式的,注意前后还有多余的字符
wocao??///啦啦啦={"song_list:{"artist_id":"88","bitrate_fee":{\"0\":\"0|0\",\"1\":\"0|0\"}","song_id":"539843843","title":"\u52a8\u7269\u4e16\u754c","ting_uid":"2517","author":"\u859b\u4e4b\u8c26","album_id":"539843841","album_title":"\u52a8\u7269\u4e16\u754c","is_first_publish":0,"havehigh":2,"charge":0,"has_mv":0,"learn":0,"song_source":"web","piao_id":"0","korean_bb_song":"0","resource_type_ext":"0","mv_provider":"0000000000","artist_name":"\u859b\u4e4b\u8c26"}}12
怎么转成json字典?
假设 str 就是上面那段话,先移除前后多余的字符
str = str!.substring(from: str!.index(str!.startIndex, offsetBy: 14))
subString 方法被废弃了,可以替换成 str = String(str![str!.index(str!.startIndex, offsetBy: 14)...]):
str!.remove(at: str!.endIndex)
str!.remove(at: str!.endIndex)
好了,现在是正确的 json 字典格式的字符串
先转为 Data,再转为 Dictionary:
let jsData = str!.data(using: .utf8)
let info = try?JSONSerialization.jsonObject(with: jsData!, options: .allowFragments)as!NSDictionary
let songlist = info!["song_list"] as!NSDictionary // 这里的 info 已经是字典了,从字典里再取值。
成功