skip to Main Content

I’m new in IOS programming.
I have a json array described with code below.

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? 
     NSDictionary
print("json: (String(describing: json))")

Output of code is;

json: Optional({
vendors =     (
            {
        firm = "XXX firm";
        id = 1;
        "show_firm" = 1;
    },
            {
        firm = "ZZZZZ firm";
        id = 2;
        "show_firm" = 1;
    }
  );
})

I want to add only firm values to another array like firms = ["XXX firm" , "ZZZZZ firm"]

How can I do that?

Any help would be greatly appreciated.

@witek bobrowski asked String(data: data!, encoding: .utf8) output.This output is below also. By the way json data comes from server as http post response.

json2: Optional("{"vendors":[{"id":"1","firm":"XXX firm","show_firm":"1"},{"id":"2","firm":"ZZZZZ firm","show_firm":"1"}]}")

3

Answers


  1. Chosen as BEST ANSWER

    I answered my own question again. There are 2 answers given but i didn't use any of these in my code. May be these two answers are usable but because of i'm new in IOS i couldn't use any of them. At the end of long google search i solved my problem as below.

    let vendors = json!["vendors"]! as! [[String : AnyObject]]
                    
                    for firm in vendors {
                        let firm1 = firm["firm"]! as! String
                        self.providerArray.append(firm1)
                       
                    }
    

    I hope this answer solves someone else's problem like me.


  2. I believe the best way to go is to decode the JSON and then add the firms value to an array.

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

    Since you have not posted your son structure, I can only assume you have a Json where vendor is an array of jsons. firmsArray is what you are looking for.
    If this doesn’t work is probably because of the wrong model and decodingModel. If you post your json structure, I will update the code so that you can properly decode your json

    Login or Signup to reply.
  3. 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)")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search