【问题标题】:Converting String to JSONArray with SwiftyJson crashes使用 SwiftyJson 将字符串转换为 JSONArray 崩溃
【发布时间】:2016-03-14 16:56:14
【问题描述】:

我已经饱和地寻找其他解决方案,但没有一个可行,所以这里是: 我想把这个 STRING VALUE 转换成 JSONObject 或 JSONArray:

[["demo": "Default", "tint": "ff00fd", "icon": "http://someurl.com/icon.jpg", "language": "en-US", "endpoint": "http://pres.artifutions.com/traveldemoapp/", "title": "Travel Demo"], ["demo": "Demo 2", "tint": "ff99fd", "icon": "http://someurl.com/icon.jpg", "language": "en-US", "endpoint": "http://pres.artifutions.com/traveldemoapp/", "title": "Second Demo"], ["demo": "Demo 3", "tint": "ff99fd", "icon": "http://someurl.com/icon.jpg", "language": "en-US", "endpoint": "http://pres.artifutions.com/traveldemoapp/", "title": "Third Demo"], ["demo": "Demo 4", "tint": "ff99fd", "icon": "http://someurl.com/icon.jpg", "language": "en-US", "endpoint": "http://pres.artifutions.com/traveldemoapp/", "title": "Fourth Demo"], ["title": "zz", "tint": "ff00fd", "icon": "(default)", "language": "nld-NLD", "endpoint": "http://pres.artifutions.com/traveldemoapp/", "demo": "z"], ["demo": "Add Demo..."]]

当我尝试使用此代码将该字符串转换为 JSON 对象时,它会崩溃:

let jConfigs = JSON(myString).array
        print("=======json")
        print(jConfigs![0])

有什么问题?将其转换为 Dictionary<String,String> 对我来说也可以。

更新: 接受的答案有效,我使用 replace() 来清理输入字符串。 另外,我做了一个额外的步骤来完成将 String 转换为 JSON 数组。请注意,在我的情况下,我无法控制字符串是如何出现的,它是-is-。

            var ss=InputString.replace("], [",withString: "}, {")
            ss=ss.replace("[[",withString: "[{")
            ss=ss.replace("]]",withString: "}]")
            if let data = ss.dataUsingEncoding(NSUTF8StringEncoding){
                do{
                    if let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)  as? [AnyObject] {
                       print(array)
                       }
                    }
                 }

【问题讨论】:

  • 什么字符串?我看到一个字典数组,而不是 JSON 字符串。你想要Dictionary<String,String>,但它已经是[Dictionary<String,String>],你不需要SwiftyJSON,只需访问数组即可。此问题中没有 JSON。
  • @EricD。它是一个字符串,在任何情况下都是 [Dictionary] 的字符串表示形式。问题是:如何将其转换为 JSON 对象或 Dictionary 对象?
  • @EricD。它就在那里,如果您不浏览我已在其下划线的阅读内容。

标签: ios arrays json swift swifty-json


【解决方案1】:

您提供的 json 格式无效。

更正一个(对象用大括号):

[{“demo”:“Default”,“tint”:“ff00fd”,“icon”:“http://someurl.com/icon.jpg”,“language”:“en-US”,“endpoint ": "http://pres.artifutions.com/traveldemoapp/", "title": "旅游演示"}, {"demo": "Demo 2", "tint": "ff99fd", "icon": "http://someurl.com/icon.jpg", "language": "en-US", "endpoint": "http://pres.artifutions.com/traveldemoapp/", "title": "第二次演示"}]

【讨论】:

  • 你在哪里对,故障不那么明显,我无法控制字符串是如何到达的。此外,对于那些感兴趣的人,我添加了一个额外的步骤,将整个东西转换为 JSON 形状的数组。
猜你喜欢
  • 1970-01-01
  • 2015-02-16
  • 1970-01-01
  • 2016-08-12
  • 2023-03-21
  • 1970-01-01
  • 2013-03-30
  • 2011-09-21
  • 2012-04-28
相关资源
最近更新 更多