ios 如何使用 SwiftyJSON 解析字符串数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27102666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:47:06  来源:igfitidea点击:

how to parse string array with SwiftyJSON?

iosjsonswift

提问by The Nomad

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

使用SwiftyJSON如何将以下 JSON 数组解析为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.

处理这个问题的最佳方法是什么?谢谢你。

回答by Gwendle

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

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

使用 SwiftyJSON,您可以获得一组 JSON 对象:

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'

然后,函数式编程使您可以轻松地使用 'map' 函数将其转换为 [String]。SwiftyJson 让你用下标“.string”来转换字符串类型

var stringArr:[String] = JSON["myArray"].arrayValue.map { 
for obj in json["array"] {
    println(obj.stringValue)
}
.stringValue}

回答by jfgrang

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

如果类型不匹配,SwiftyJSON 允许您提取String?using $0.string 或非可选Stringusing stringValue 和默认空 String 值。

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 })

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

or in Swift 4.1

或在 Swift 4.1

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

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

You can also replace self.json["array"].arrayby self.json["array"].arrayValueto have a [String]result instead of [String]?.

您也可以替代self.json["array"].arrayself.json["array"].arrayValue[String]结果,而不是[String]?

回答by Jeffery Thomas

You have a Dictionarywhich holds an Arraywhich holds Strings. When you access a value in the Dictionary, it returns a simple Arrayof Strings. You iterate it like you would any array.

你有一个Dictionary持有一个Array持有Strings。当您访问 中的值时Dictionary,它返回一个简单ArrayStrings。你像迭代任何数组一样迭代它。

for stringInArray in json["array"]{

    let value = stringInArray.1.stringValue
}

回答by Yaron Levi

Simply do this:

只需这样做:

##代码##