繁体   English   中英

使用Swift和SwiftyJSON解析JSON字符串

[英]Parse JSON String using Swift and SwiftyJSON

我试图解析使用循环快速创建的字符串。 我将其制成字符串,然后我就厌倦了使用Swifty JSON将字符串转换为JSON。 当我尝试遍历json时,我的代码从不进入循环。 我怀疑存在数据类型问题,但我被卡住了。 任何帮助,将不胜感激。 这是我创建为字符串的json结构

 [{
    "category_name": "AIR SYSTEM",
    "cntpassed": 0,
    "cntfailed": 0,
    "isfailed": 0,
    "isstarted": 1,
    "iscomplete": 1,
    "isnotcomplete": 0,
    "cnttotal": 5
}, {
    "category_name": "ENGINE COMPARTMENT",
    "cntpassed": 0,
    "cntfailed": 0,
    "isfailed": 0,
    "isstarted": 1,
    "iscomplete": 1,
    "isnotcomplete": 0,
    "cnttotal": 27
}, {
    "category_name": "EXTER.",
    "cntpassed": 0,
    "cntfailed": 0,
    "isfailed": 0,
    "isstarted": 1,
    "iscomplete": 1,
    "isnotcomplete": 0,
    "cnttotal": 3
}]

我使用swifty json方法将其转换为json

let json = JSON(jsonStringAbove)

然后我试图快速遍历

public func jsonFormSectionsArray(jsonString: String) -> Array<String>
 {
     print("In jsonFormsSectionArray")
     var anArray: [String] = []
     let json = JSON(jsonString)

     print("\nHeres the JSON \(json)")

     for (key, subJson) in json {
         // My code never gets to this point
         if let category = subJson["category_name"].string {
             print(category)
             anArray.append(category)
         }
     }

         print("PETE --> In Function Array \(anArray)")
         return anArray
 }

您的JSON看起来像是一个字典数组,因此您无法使用键值对对其进行迭代。 您需要遍历数组。 您无需手动遍历字典的每个键-值对,如果您知道键,则可以直接查找值。

我不确定SwiftyJSON创建的JSON如何表示,但是如果它是字典数组,那么就可以正常工作。

for dictionary in json {
     if let category = dictionary["category_name"] as? String {
         print(category)
         anArray.append(category)
     }
 }

暂无
暂无

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

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