arrays - 如何将特定的 JSON 值添加到 Swift 中的另一个数组?
问题描述
我是IOS编程的新手。我有一个用下面的代码描述的 json 数组。
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as?
NSDictionary
print("json: \(String(describing: json))")
代码的输出是;
json: Optional({
vendors = (
{
firm = "XXX firm";
id = 1;
"show_firm" = 1;
},
{
firm = "ZZZZZ firm";
id = 2;
"show_firm" = 1;
}
);
})
我只想将公司值添加到另一个数组中,例如公司 = [“XXX 公司”,“ZZZZZ 公司”]
我怎样才能做到这一点?
任何帮助将不胜感激。
@witek bobrowski 询问 String(data: data!, encoding: .utf8) 输出。这个输出也在下面。顺便说一句,json数据来自服务器作为http post响应。
json2: Optional("{\"vendors\":[{\"id\":\"1\",\"firm\":\"XXX firm\",\"show_firm\":\"1\"},{\"id\":\"2\",\"firm\":\"ZZZZZ firm\",\"show_firm\":\"1\"}]}")
解决方案
the best way is to create Decodable Model for your json as below:
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"
}
}
I created this factory method to simulate your json response locally based on what you provided in the question
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
}
}
}
now you will be able to map only the firm names as you request you can test like this
let firmNames = FirmFactory.makeFirms()?.map { $0.name }
print("firmNames \(firmNames)")
推荐阅读
- arrays - 根据条件收集过滤对象的所有属性名称
- php - PHP`use`导入命名空间导致页面崩溃
- python - ignore_index 和 concat() 的问题
- javascript - 正则表达式查找具有给定属性的 React JSX 元素?
- javascript - BulkWriteError: E11000 重复键错误收集
- swift - 我怎样才能从另一个故事板返回包含 TabBarController 的 Main.storyboard
- ruby-on-rails - 创建具有 has_one 关系的 FactoryBot 用户
- swift4.2 - Swift4.2 不支持 stdatomic - 原子布尔值的简单实现是什么?
- mongodb - 在 MongoDB 中存储最近使用的项目的设计方法
- azure-durable-functions - Azure Durable Functions 大消息支持问题