Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse string array with SwiftyJSON?

Tags:

json

ios

swift

Using SwiftyJSON how would I parse the following JSON array into a Swift [String]?

{
    "array": ["one", "two", "three"]
}

I have tried this code, but it doesn't work for me:

for (index: String, obj: JSON) in json["array"] {
        println(obj.stringValue)
    }

What would be the best way to handle this? Thank you.

like image 699
The Nomad Avatar asked Nov 24 '14 10:11

The Nomad


People also ask

How do I add SwiftyJSON to Xcode?

Adding SwiftyJSON to the demo project Here's our path: Xcode > ( Xcode project name) > Targets > (Xcode project name). In the General tab, under the Frameworks and Libraries dropdown, we click on + and select Add package dependency. Then, we enter the package Git URL: https://github.com/SwiftyJSON/SwiftyJSON.git.


2 Answers

{
    "myArray": ["one", "two", "three"]
}

Using SwiftyJSON, you can get an array of JSON objects with:

var jsonArr:[JSON] = JSON["myArray"].arrayValue

Functional programming then makes it easy for you to convert to a [String] using the 'map' function. SwiftyJson let's you cast string type with subscript '.string'

var stringArr:[String] = JSON["myArray"].arrayValue.map { $0.stringValue}
like image 128
Gwendle Avatar answered Oct 14 '22 12:10

Gwendle


SwiftyJSON lets you extract a String? using $0.string or a non optional String using stringValue with a default empty String value if the type doesn't match.

If you want to be sure to have an array of String with non false positives, use :

var stringArray = self.json["array"].array?.flatMap({ $0.string })

or in Swift 4.1

var stringArray = self.json["array"].array?.compactMap({ $0.string })

You can also replace self.json["array"].array by self.json["array"].arrayValue to have a [String] result instead of [String]?.

like image 9
jfgrang Avatar answered Oct 14 '22 13:10

jfgrang