简体   繁体   中英

Parse JSON String using Swift and SwiftyJSON

I am trying to parse a string I manually created in swift using loops. I made it as a string, then I tired to use Swifty JSON to turn that string into json. When I try to loop through the json, my code never enters the loop. I suspect there is a data type issue but I am stuck. Any help would be appreciated. Here is the json structure that I created as a string

 [{
    "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
}]

I turn it into json using swifty json method

let json = JSON(jsonStringAbove)

Then I tried to loop through it in swift

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
 }

Your JSON looks like an array of dictionaries, so you can't iterate through it with key-value pairs. You need to iterate through the array. You don't need to manually iterate through each key-value pair of the dictionary, you can directly look up a value if you know the keys.

I am not sure how is the JSON created by SwiftyJSON represented, but if it's an array of dictionaries, this works just fine.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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