![](/img/trans.png)
[英]How can I identify consecutive occurrences of a specific value in an array in Swift?
[英]How can i add specific JSON value to another array in Swift?
我是 IOS 编程新手。 我有一个 json 数组,用下面的代码描述。
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as?
NSDictionary
print("json: \(String(describing: json))")
Output的代码是;
json: Optional({
vendors = (
{
firm = "XXX firm";
id = 1;
"show_firm" = 1;
},
{
firm = "ZZZZZ firm";
id = 2;
"show_firm" = 1;
}
);
})
我只想将公司值添加到另一个数组中,例如公司 = [“XXX 公司”,“ZZZZZ 公司”]
我怎样才能做到这一点?
任何帮助将不胜感激。
@witek bobrowski 询问字符串(数据:数据,:编码。.utf8)output。这个 output 也在下面。 顺便说一句,json 数据来自服务器作为 http 后响应。
json2: Optional("{\"vendors\":[{\"id\":\"1\",\"firm\":\"XXX firm\",\"show_firm\":\"1\"},{\"id\":\"2\",\"firm\":\"ZZZZZ firm\",\"show_firm\":\"1\"}]}")
我相信 go 的最佳方法是解码 JSON 然后将公司值添加到数组中。
struct model: Decodable{
var vendors: [decodingModel]
}
struct decodingModel: Decodable{
var firm: String
var id: Int
var show_firm: Int
}
let decoder = JSONDecoder()
do{
let result = try decoder.decode(model.self, from: jsonData)
let firmsArray = result.vendors.compactMap({$0.firm})
}catch{
print(error)
}
由于您尚未发布您的儿子结构,我只能假设您有一个 Json ,其中 vendor 是一个 json 数组。 firmsArray
是您正在寻找的。 如果这不起作用可能是因为错误的model
和decodingModel
模型。 如果您发布您的 json 结构,我将更新代码,以便您可以正确解码您的 json
最好的方法是为您的 json 创建 Decodable Model,如下所示:
struct Firm: Decodable {
let id: Int
let name: String
let showFirm: Int
enum CodingKeys: String, CodingKey {
case id
case name = "firm"
case showFirm = "show_firm"
}
}
我创建了这个工厂方法来根据您在问题中提供的内容在本地模拟您的 json 响应
struct FirmFactory {
static func makeFirms() -> [Firm]? {
let json = [
[
"firm": "XXX firm",
"id": 1,
"show_firm": 1,
],
[
"firm": "ZZZZZ firm",
"id": 2,
"show_firm": 1,
],
]
// you should use the following code to decode and parse your real json response
do {
let data = try JSONSerialization.data(
withJSONObject: json,
options: .prettyPrinted
)
return try JSONDecoder().decode([Firm].self, from: data)
} catch {
print("error \(error.localizedDescription)")
return nil
}
}
}
现在您将能够 map 只有您要求的公司名称,您可以像这样测试
let firmNames = FirmFactory.makeFirms()?.map { $0.name }
print("firmNames \(firmNames)")
我再次回答了我自己的问题。 给出了 2 个答案,但我没有在我的代码中使用任何这些。 可能这两个答案是可用的,但由于我是 IOS 的新手,我无法使用其中任何一个。 在长时间的谷歌搜索结束时,我解决了我的问题,如下所示。
let vendors = json!["vendors"]! as! [[String : AnyObject]]
for firm in vendors {
let firm1 = firm["firm"]! as! String
self.providerArray.append(firm1)
}
我希望这个答案可以解决像我这样的其他人的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.