我有一个json字符串(text2
):
" {\" MSGTYPE \":103,\"消息\":\" {\" UserObject \&#34 ;:{\"的SecretID \":\" dsofgihsdaoifhad = \" \"姓\":\" ASDGF \&#34 ; \"名字\":\" HDSA \" \" IsFemale \":0,\" PhoneOffice \&#34 ;:\" \" \" ISDCode \":\" \" \" PhonePersonal \":\& #34; 91923426989 \" \"指定\":\" \" \"公司\":\" \" \"标语\":\"帮助 mplemented \" \" FBID \":\" \" \" FbURL \":\" \&# 34; \" FbToken \":\" \" \" GplusId \":\" \" \ " GplusURL \":\" \" \" GplusToken \":\" \" \" LinkedinId \":\" \" \" LinkedinURL \":\" \" \" LinkedinToken \&# 34;:\" \" \"状态\":\" \" \"电子邮件\":\ " \" \" DisplayPicture \":\" \" \" IsPrivatePhoneOffice \":0,\&# 34; IsPrivatePhonePersonal \":1,\" IsPrivateEmail \":0,\"设备类型\":\"机器人\" \ " NotificationRegistrationID \":\" APA9HZ_RmEy7gfbQtN-QBxXr7dafG394oT9Dg1HpAv7OaWbUsMOsfpMI1a_7Qa2aNkqBOWB3M29djtsRW0fWl4oZSG0bwVv1zEPDBAseZvv1eHfqVj_JUI8tZixX \" \"位置\":\" \" \& #34;纬度\":18.69943,\"经度\":77.12576,\" IsPrivate \":0},\" ConnectionStatus \&# 34;:3,\" ConnectionType \":1,\" PreviousMeetings \":[{\"的SecretID \":\" sadfosdfjasdf = \" \" FriendSecretId \":\" dsofgihsdaoifhad = \" \" MeetingTime \":1447088420440,\&#34 ;状态\":\" \" \" MeetingNotes \":\" \" \"位置\& #34;:\" \" \"纬度\":28.6994,\"经度\":77.1258,\" ContactType \ ":\" \"},{\"的SecretID \":\" sadfosdfjasdf = \" \" FriendSecretId \ ":\" dsofgihsdaoifhad = \" \" MeetingTime \":1447088335275,\"状态\":\" \ " \" MeetingNotes \":\" \" \"位置\":\" \" ,\"纬度\":28.6994,\"经度\":77.1258,\" ContactType \":\" \&#34 ;},{\"的SecretID \":\" sadfosdfjasdf = \" \" FriendSecretId \":\" dsofgihsdaoifhad = \& #34; \" MeetingTime \":1447088229120,\"状态\":\" \" \" MeetingNotes \&# 34;:\" \" \"位置\":\" \" \"纬度\":28.6994 ,\"经度\":77.1258,\" ContactType \":\" \"},{\&#34 ;的SecretID \":\" sadfosdfjasdf = \" \" FriendSecretId \":\" dsofgihsdaoifhad = \" \&#34 ; MeetingTime \":1447088014838,\"状态\":\" \" \" MeetingNotes \":\" \" \"位置\":\" \" \"纬度\":28.6994,\"经度\ ":77.1258,\" ContactType \":\" \"},{\"的SecretID \":\" sadfosdfjasdf = \" \" FriendSecretId \":\" dsofgihsdaoifhad = \" \" MeetingTime \":1444547028931,\&#34 ;状态\":\" \" \" MeetingNotes \":\" \" \"位置\& #34;:\" \" \"纬度\":28.6994,\"经度\":77.1258,\" ContactType \ ":\" \"}]} \"}"
它包含一个包含2个字段的json对象:MsgType
和Msg
。 Msg
进一步包含字符串形式的序列化json对象。
我需要将MsgType
的值读作数字,将Msg
作为json对象读取。
我尝试了几件事:
首先:
if let dataFromString = text2.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
print("swiftyjson:\(json)")
}
来源:https://github.com/SwiftyJSON/SwiftyJSON#initialization
输出:
swiftyjson:空
其次:
let data = text2.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do {
let jsonSys = try NSJSONSerialization.JSONObjectWithData(data, options: [])
print("jsonSys:\(jsonSys)")
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
输出:
无法加载:无法读取数据,因为它不在 格式正确。
答案 0 :(得分:1)
您的JSON字符串未正确转义。
{
不应该以双引号开头,它应该是这样的:" {\" MSGTYPE \":103,\"消息\":{\" UserObject \" ...
... 77.1258,\" ContactType \":\" \"}]}}"