iOS 把String字符串转化为json字符串-subString截取字符串-index操作

这里假设有一大串字符串,格式是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 已经是字典了,从字典里再取值。

成功

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值