使用SwiftyJson崩溃将String转换为JSONArray

时间:2016-03-14 16:56:14

标签: ios arrays json swift swifty-json

我已经饱和了寻找其他解决方案,但没有一个会起作用,所以在这里: 我想转换此 STRING VALUE ,我重复: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)
                       }
                    }
                 }

1 个答案:

答案 0 :(得分:1)

您提供了无效的json格式。

纠正一个(对象的花括号):

[ {&#34;演示&#34;:&#34;默认&#34;,&#34;色彩&#34;:&#34; ff00fd&#34;,&# 34; icon&#34;:&#34; http://someurl.com/icon.jpg&#34;,&#34;语言&#34;:&#34; en-US&#34;,&#34;端点&#34;: &#34; http://pres.artifutions.com/traveldemoapp/&#34;,&#34; title&#34;:&#34;旅行演示&#34; } {& #34;演示&#34;:&#34;演示2&#34;,&#34; tint&#34;:&#34; ff99fd&#34;,&#34; icon&#34;:&#34; { {3}}&#34;,&#34;语言&#34;:&#34; zh-CN&#34;,&#34;端点&#34;:&#34; http://someurl.com/icon.jpg&#34 ;,&#34; title&#34;:&#34; Second Demo&#34; } ]