首页 > 解决方案 > 如何将特定的 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\"}]}")

标签: arraysjsonswiftxcode

解决方案


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

推荐阅读