I have a string that looks like JSON and I need to turn it into objects. The string is
[{"name":"Samuro","title":"The Blademaster","role":{"name":"Assassin","slug":"assassin"},"type":{"name":"Melee","slug":"melee"},"stats":{"damage":0,"utility":0,"survivability":0,"complexity":0},"slug":"samuro","franchise":"warcraft","analyticsName":"Samuro","trait":{},"skins":[],"abilities":[],"heroicAbilities":[],"revealed":true,"inFreeHeroRotation":false,"freeRotationMinLevel":0},{"name":"Zarya","title":"Defender of Russia","role":{"name":"Warrior","slug":"warrior"},"type":{"name":"Ranged","slug":"ranged"},"stats":{"damage":0,"utility":0,"survivability":0,"complexity":0},"slug":"zarya","franchise":"overwatch","analyticsName":"Zarya","trait":{},"skins":[],"abilities":[],"heroicAbilities":[],"revealed":true,"inFreeHeroRotation":false,"freeRotationMinLevel":0}]
When I put the string into a json formatter like the one at https://jsonformatter.curiousconcept.com it comes out perfectly formatted like its already in json format. However when i try
for element in jsonString {
let jsonHero = JsonHero(fromDictionary: element as! [String: AnyObject])
testingArray.append(jsonHero)
}
and treat it like json data that i would get from
json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments) as! [[String: AnyObject]]
it obviously doesn't work because a string doesn't have elements.
I've tried using an extension to convert my string to json but that didnt work. I'm new to programming so I don't know if the extension was bad or thats not what i need to do.
How can I get my string to work like json data (if thats what its called) so i can put it into objects?
convert string to NSData
let responseData: NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
NS Serialization
var dummyJson: [[String: AnyObject]]!
do {
dummyJson = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments) as! [[String: AnyObject]]
}
catch {
//handle error
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.