如何将String转换为JSON,以便将其解析为对象

时间:2016-10-06 23:20:59

标签: ios json swift parsing

我有一个看起来像JSON的字符串,我需要把它变成对象。字符串是

[{"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}]

当我将字符串放入像https://jsonformatter.curiousconcept.com那样的json格式化程序时,它的格式就像它已经是json格式一样。但是当我尝试

for element in jsonString {
            let jsonHero = JsonHero(fromDictionary: element as! [String: AnyObject])
            testingArray.append(jsonHero)   
        }

并将其视为我将从

获得的json数据
json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments) as! [[String: AnyObject]]
它显然不起作用,因为字符串没有元素。

我已经尝试使用扩展程序将我的字符串转换为json但是没有用。我是编程新手,所以我不知道扩展是坏的还是不是我需要做的。

如何让我的字符串像json数据一样工作(如果那就是它的名字),这样我可以把它放到对象中?

1 个答案:

答案 0 :(得分:0)

将字符串转换为NSData

let responseData: NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!

NS序列化

var dummyJson: [[String: AnyObject]]!
        do {
            dummyJson = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments) as! [[String: AnyObject]]
        }
        catch {
            //handle error
        }