简体   繁体   English

更新值-SwiftyJSON

[英]Updating value - SwiftyJSON

I have a json object as below 我有一个JSON对象如下

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

I have this json data in my project folder and I am using SwiftyJSON to parse my son and read the values. 我的项目文件夹中有这个json数据,我正在使用SwiftyJSON解析儿子并读取值。 Everything looks fine. 一切看起来都很好。

Now I need to update the score and I am trying as below 现在我需要更新分数,我正在尝试如下

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

This works fine too and the json is updated but below try fails 这也可以正常工作,并且json已更新,但在下面尝试失败

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

I get compile error 我得到编译错误

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

Any suggestion on how to update a SwiftJSON JSON object with a variable would be helpful 关于如何使用变量更新SwiftJSON JSON对象的任何建议都将有所帮助

Thank you 谢谢

Update:My Solution 更新:我的解决方案

This is what I have done finally 这就是我最后做的

    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!)

And this works 这有效

如果要将json保存为字典,请尝试以下操作

((json["level"]as nsdictionary)["score"] as NSString = updatedScore)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM