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
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.
I hope this answer solves someone else's problem like me.
I believe the best way to go is to decode the JSON and then add the firms value to an array.
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
anddecodingModel
. If you post your json structure, I will update the code so that you can properly decode your jsonthe best way is to create Decodable Model for your json as below:
I created this factory method to simulate your json response locally based on what you provided in the question
now you will be able to map only the firm names as you request you can test like this