How to i insert a JSON object into an array? - ios

I have a JSON
"passengers": [{
"accompaniedByInfant": true,
"birthDate": {
"day": 6,
"fractionalSecond": 0.000,
"hour": 0,
"minute": 0,
"month": 9,
"orig_day": 6,
"orig_fracSeconds": 0.000,
"orig_hour": 0,
"orig_minute": 0,
"orig_month": 9,
"orig_second": 0,
"orig_timezone": 330,
"orig_year": 1991,
"second": 0,
"timezone": 330,
"year": 1991
},
"hasStrecher": false,
"parentSequence": 0,
"passengerTypeCode": "ADLT",
"gender":"M"
"personName": {
"givenName": "v",
"nameTitle": "MR",
"shareMarketInd": false,
"surname": "j"
},
"requestedSeatCount": 1,
"shareMarketInd": false,
"unaccompaniedMinor": false
}, {
"accompaniedByInfant": false,
"birthDate": {
"day": 10,
"fractionalSecond": 0.000,
"hour": 0,
"minute": 0,
"month": 10,
"orig_day": 10,
"orig_fracSeconds": 0.000,
"orig_hour": 0,
"orig_minute": 0,
"orig_month": 10,
"orig_second": 0,
"orig_timezone": 330,
"orig_year": 2010,
"second": 0,
"timezone": 330,
"year": 2010
},
"hasStrecher": false,
"parentSequence": 0,
"passengerTypeCode": "CHLD",
"personName": {
"givenName": "some",
"shareMarketInd": false,
"surname": "child"
},
"requestedSeatCount": 1,
"shareMarketInd": false,
"unaccompaniedMinor": false
},
and so on depending on the number of passengers.
I have to sent this to the server in
let param : [String: Any] =[ "passengers":passengerparameterarray,"pwd": password,"requestPurpose": "MODIFY_PERMANENTLY_AND_CALC","unm": username ]
Here passengerparameterarray is an array of type string.(here is the issue). I stored details of each passenger in an array
paramarray and whenever user finishes adding details, paramarray is added to the passengerparameterarray on position depending on the indexPath. (1 passenger = added on 0th index, 2 = on 0th and 1st index and so on).
But when I send it to server it goes like
"passengers" : [ [ ..... ] ]
This gives me error as I have an array inside of the array. How do I fix this? I try changing to string but that gives me error as String isn't JSON object because of the " coming before { .
I converted each array to JSON Object. But how do i JSON Object the main array? As the Main array is [String]() . If i try changing to [String:Any]() , things like
array.insert()
Wont work.
How do I fix this? I want to add the JSON object into an array and then sent it to the server.

try this
var param : [String:Any] = ["requestedSeatCount" : 1, "gender" : "M", "parentSequence" : 0, "passengerTypeCode" : "ADLT", "shareMarketInd" : false]
param.updateValue(["nameTitle" : "MR", "givenName" : "aaaa", "surname" : "aaa"], forKey: "personName")
param.updateValue(["year" : "2019", "day" : "29", "month" : "5"], forKey: "birthDate")

This was a stupid question. This all happened because originally my array was
var passengerparameterarray = [Array<Any>]()
instead of
var passengerparameterarray = Array<[String: Any]>()
Which as expected stopped me from inserting JSON object which is in the form of "String:Any"

Related

How to get the value of an array of selected keys from swift array of dictionaries and the complexity of it

Lets say I have got the below response. Two things I would like to know from the below operation.
1.) How to improve/optimise the below code using higher order functions in swift.
2.) Also would like to know the current complexity of the code and the complexity of any optimized code you may suggest.
In the below response I would like to check the values of only certain keys as described in keysToBeChecked and for that particular key I need to do an operation. Once the operation is done I want to add a new key(key6) to the response as shown below. The following operation works fine for me and that is what I intend to do. I am looking for the above 2 things mentioned
var response = [["key1": 1, "key2": 0, "name": "John", "key3": 1, "key4": 1, "place": "Newyork", "key5": 0],
["key1": 0, "key2": 1, "name": "Mike", "key3": 1, "key4": 0, "place": "California", "key5": 1],
["key1": 1, "key2": 0, "name": "John", "key3": 0, "key4": 1, "place": "Boston", "key5": 1]]
let keysToBeChecked = ["key1", "key2", "key3", "key4", "key5"]
for var item in response{
var dict = [String: String]()
for(key, value) in item{
if keysToBeChecked.contains(key){
dict[key] = "\(value)"
if dict[key] == "1"{
//perform required operations
output
}
}
}
item["key6"] = output
response.append(item)
}
print(response)//should print the below
My expected output is
response = [["key1": 1, "key2": 0, "name": "John", "key3": 1, "key4": 1, "place": "Newyork", "key5": 0, "key6": "output"],
["key1": 0, "key2": 1, "name": "Mike", "key3": 1, "key4": 0, "place": "California", "key5": 1, "key6": "output"],
["key1": 1, "key2": 0, "name": "John", "key3": 0, "key4": 1, "place": "Boston", "key5": 1, "key6": "output"]]
For higher order function, you can try,
let result = response.map { (dict) -> [String:Any] in
var filteredDict = [String:Any]()
dict.forEach({ (key, value) in
if keysToBeChecked.contains(key) {
filteredDict[key] = value
if (value as? Int) == 1 {
filteredDict["key6"] = "output"
}
}
})
return filteredDict
}

Highcharts spiderweb showing wrong categories at first position

On the y-axis of the spider chart, it reads 0, 100, 20, 30, ...
While the interval is 10 and max value is 100.
How can I make sure Highcharts shows the correct order: 0, 10, 20, ..., 100.
This is a fiddle to show the issue I'm having: https://jsfiddle.net/8g9q3ubd/
"yAxis": {
"gridLineInterpolation": "polygon",
"lineWidth": 0,
"pointInterval": 10,
"min": 0,
"max": 100,
"tickAmount": 10,
"tickInterval": 10,
"tickmarkPlacement": "on",
"categories": ["0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"]
},
You do not need to use categories property. With tickInterval: 10 only every tenth category is shown and your last category ("100") is shown in second place.
"yAxis": {
"gridLineInterpolation": "polygon",
"lineWidth": 0,
"pointInterval": 10,
"min": 0,
"max": 100,
"tickAmount": 11,
"tickInterval": 10,
"tickmarkPlacement": "on"
}
Live demo: https://jsfiddle.net/BlackLabel/fmo31h7n/
API Reference: https://api.highcharts.com/highcharts/yAxis.categories

How do i create and sent a JSON to the server using Alamofire?

I want to sent a JSON to the server,with details of user and options selected by the user. Currently i just save those in simple arrays.
I want to create a JSON and sent it to the server. Normally i can just add each those fields on Parameter with Alamofire. But here i have an issue is that, the number of fields depend on the number of users(or passenger count).
I haven't done this type before and i am a newbie into iOS developing.
{
"contactPerson": {
"email": {
"email": "memine#gmail.com",
"markedForSendingRezInfo": false,
"preferred": false,
"shareMarketInd": false
},
"personName": {
"givenName": "Me",
"shareMarketInd": false,
"surname": "Mine"
},
"phoneNumber": {
"countryCode": "93",
"markedForSendingRezInfo": false,
"preferred": false,
"shareMarketInd": false,
"subscriberNumber": "123456789"
},
"shareMarketInd": false,
"useForInvoicing": false
},
"curr": "USD",
"flight1": "{fligh1Info}",
"flight2": "{flight2Info}",
"passengers": [{
"accompaniedByInfant": true,
"birthDate": {
"day": 6,
"fractionalSecond": 0.000,
"hour": 0,
"minute": 0,
"month": 9,
"orig_day": 6,
"orig_fracSeconds": 0.000,
"orig_hour": 0,
"orig_minute": 0,
"orig_month": 9,
"orig_second": 0,
"orig_timezone": 330,
"orig_year": 1991,
"second": 0,
"timezone": 330,
"year": 1991
},
"hasStrecher": false,
"parentSequence": 0,
"passengerTypeCode": "ADLT",
"personName": {
"givenName": "some",
"nameTitle": "Mr.",
"shareMarketInd": false,
"surname": "guy"
},
"requestedSeatCount": 1,
"shareMarketInd": false,
"unaccompaniedMinor": false
}, {
"accompaniedByInfant": false,
"birthDate": {
"day": 10,
"fractionalSecond": 0.000,
"hour": 0,
"minute": 0,
"month": 10,
"orig_day": 10,
"orig_fracSeconds": 0.000,
"orig_hour": 0,
"orig_minute": 0,
"orig_month": 10,
"orig_second": 0,
"orig_timezone": 330,
"orig_year": 2010,
"second": 0,
"timezone": 330,
"year": 2010
},
"hasStrecher": false,
"parentSequence": 0,
"passengerTypeCode": "CHLD",
"personName": {
"givenName": "some",
"shareMarketInd": false,
"surname": "child"
},
"requestedSeatCount": 1,
"shareMarketInd": false,
"unaccompaniedMinor": false
}, {
"accompaniedByInfant": false,
"birthDate": {
"day": 1,
"fractionalSecond": 0.000,
"hour": 0,
"minute": 0,
"month": 1,
"orig_day": 1,
"orig_fracSeconds": 0.000,
"orig_hour": 0,
"orig_minute": 0,
"orig_month": 1,
"orig_second": 0,
"orig_timezone": 330,
"orig_year": 2018,
"second": 0,
"timezone": 330,
"year": 2018
},
"hasStrecher": false,
"parentSequence": 0,
"passengerTypeCode": "INFT",
"personName": {
"givenName": "some",
"shareMarketInd": false,
"surname": "kid"
},
"requestedSeatCount": 1,
"shareMarketInd": false,
"unaccompaniedMinor": false
}],
"pwd": "password",
"requestPurpose": "MODIFY_PERMANENTLY_AND_CALC",
"unm": "username"
}
This is my JSON. Here number of flight1 flight2 .... depends on number of flights picked by the user.
and number of objects inside passengers depends on number of passengers selected by the user.
How do i do this part?
Try to create a dictionary of [String: Any] type like below example.
let param : [String: Any] = ["contactPerson": [ "email":[ "email": "text#mail.com"], "markedForSendingRezInfo": false], "personName": [], "curr": "USD", "flight1" : [], "flight2" : [] ]
You can add key value in param as per request parameter requirement. then pass this param to alamofire request param.
You need to add your data in Dictionary
Swift5
let dictData = ["name": "vicky", "phoneNumber": "01234567"]
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dictData) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
}

Swift 4 - How to structure a json object and using decodable in switch (not working)

I'm trying to create a structure for the following json object using swift decodable.
{
"template": [
{
"id": 8,
"question": "Favorite Color?",
"category": "Color",
"section": "Favorite Colors",
"is_active": 1,
},
[
{
"id": 14,
"question_id": 8,
"option_name": "Red",
"is_active": 1,
},
{
"id": 16,
"question_id": 8,
"option_name": "Orange",
"is_active": 1,
}
],
{
"id": 9,
"question": "What cars do you drive?",
"category": "Cars",
"section": "Favorite Cars",
"is_active": 1,
},
[
{
"id": 15,
"question_id": 9,
"option_name": "Toyota",
"is_active": 1,
},
{
"id": 18,
"question_id": 9,
"option_name": "Honda",
"is_active": 1,
},
{
"id": 19,
"question_id": 9,
"option_name": "BMW",
"is_active": 1,
}
]
]
}
I have some like:
public struct GameTemplate:Decodable {
question:String?
}
public struct Game:Decodable {
let template[GameTemplate]
}
For some reason when i tried to parse it doesn't work i get an error stating that struct is not a dictionary. I have tried casting the struct value but that didn't work either at this point just need to get a nice and clean json object after is decoded.
your JSON format is not consistent.
Just take the first category of color :
{
"template": [
{
"id": 8,
"question": "Favorite Color?",
"category": "Color",
"section": "Favorite Colors",
"is_active": 1,
},
[
{
"id": 14,
"question_id": 8,
"option_name": "Red",
"is_active": 1,
},
{
"id": 16,
"question_id": 8,
"option_name": "Orange",
"is_active": 1,
}
],
]
}
The template is an array having dictionary on 0 index and array on 1 index.
It is decodable in a different way but that's an extra effort.
If possible make the JSON data consistent and club categories in one index of array as :
{
"template": [
{
"id": 8,
"question": "Favorite Color?",
"category": "Color",
"section": "Favorite Colors",
"is_active": 1,
"subCategory": [
{
"id": 14,
"question_id": 8,
"option_name": "Red",
"is_active": 1,
},
{
"id": 16,
"question_id": 8,
"option_name": "Orange",
"is_active": 1,
}
]
}
]
}
and the same way club the different category of cars.
It will be easy for you to decode as:
public struct GameTemplate:Decodable {
question: String?
subCategory: [SubCategory]
}
public struct SubCategory:Decodable {
option_name: String?
}
public struct Game:Decodable {
let template: [GameTemplate]
}
Hope you get it what I am trying to explain.

Access nested array of array of dictionary

I want to display the value of "description" on table view but I am not able to reach to the "description". Every time I loop it. Example
for i in item {
let result = i["description"]
}
It returns Type 'Any' has no subscript members
[[["description": "Meeting", "comments": "", "projectId": 6, "hours": 0.0, "id": 52, "projectName": "A-DA Internal"], ["description": "Others", "comments": "", "projectId": 6, "hours": 0.0, "id": 53, "projectName": "A-DA Internal"], ["description": "3.1 Project Planning", "comments": "", "projectId": 5, "hours": 0.0, "id": 28, "projectName": "STARWorks ESS"], ["description": "4.1 Analysis & Design", "comments": "", "projectId": 5, "hours": 0.0, "id": 32, "projectName": "STARWorks ESS"], ["description": "4.3 Bug fixes", "comments": "", "projectId": 5, "hours": 0.0, "id": 34, "projectName": "STARWorks ESS"]]]
From the response you have posted above its seems the type is [[[String : Any]]].
So to get to the [String: Any] part you will have to dive two level.
//let say
let result: [[[String: Any]]] = THE RESPONSE YOU POSTED..
let item = result.flatmap {$0} //this will convert to [[String: Any]]
//After that your loop will work as expected
for i in item {
debugPrint(i["description"])
}
You need to tell your compiler that the item through which you want to loop through is of type [[String:Any]] only you can get the value for the key description.
You can do that the following way:
for i in item as! [[String:Any]] {
let result = i["description"]
}
Hope this helps. For any queries feel free to leave a comment.

Resources