更新值 - SwiftyJSON

时间:2015-03-25 10:30:22

标签: ios json swift

我有一个json对象,如下所示

{"level" :{"currentLevel":"1","score":"100"}}

我在项目文件夹中有这个json数据,我使用SwiftyJSON来解析我的儿子并读取值。一切都很好。

现在我需要更新分数,我正在尝试如下

var json = JSON({"level" :{"currentLevel":"1","score":"100"}})
json["level"]["score"] = "200"

这也可以正常工作,json会更新但是下面尝试失败

var json = JSON({"level" :{"currentLevel":"1","score":"100"}})
var updatedScore:String = "200"
json["level"]["score"] = updatedScore

我收到编译错误

Type [Subscript] does not conform to Protocol 'StringLiteralConvertible'

有关如何使用变量更新SwiftJSON JSON对象的任何建议都会有所帮助

谢谢

更新:我的解决方案

这是我最后做的事情

    var json = JSON({"level" :{"currentLevel":"1","score":"100"}})
    var level = (json["level"] as JSON).dictionaryObject
    let updatedScore = "200"
    level!["currentLevel"] = updatedScore
    json["level"] = JSON(level!)

这有效

1 个答案:

答案 0 :(得分:1)

如果要将json保存为字典

,请尝试以下操作
((json["level"]as nsdictionary)["score"] as NSString = updatedScore)
相关问题