I just want to create an API JSON Structure. The following are the post body keys and objects. Are there any methods like object with keys and values similar to Objective C in Swift 4?
{
"name": "switch 1",
"type": "Switch",
"gatewayId":515,
"serialKey": "98:07:2D:48:D3:56",
"noOfGangs": 4,
"equipments": [
{
"name": "light",
"type": "Light",
"port": "1"
},
{
"name": "television",
"type": "Television",
"port": "3"
}
]
}
You can create the dictionary literally by annotating the type and replace the curly braces with square brackets
let dict : [String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4, "equipments": [[ "name": "light", "type": "Light", "port": "1" ], ["name": "television", "type": "Television", "port": "3" ]]]
Or build it:
var dict : [String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4]
var equipments = [[String:String]]()
equipments.append(["name": "light", "type": "Light", "port": "1" ])
equipments.append(["name": "television", "type": "Television", "port": "3" ])
dict["equipments"] = equipments
how to create Dictionary
var populatedDictionary = ["key1": "value1", "key2": "value2"]
this how to create Array
var shoppingList: [String] = ["Eggs", "Milk"]
you can create Dictionary by this type
var dictionary = [Int:String]()
dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)
// anather example
var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
your JSON
let dic :[String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4, "equipments": [ [ "name": "light", "type": "Light", "port": "1" ],
[ "name": "television", "type": "Television", "port": "3" ] ] ]
Related
I am having issues to successfully structure my json data into a swift dictionary inorder to send my HTTP body via an API
This is how my Json is structured:
{
"idNo": "string",
"name": "string",
"isRegistered": true,
"customMessage": "string",
"riskStatus": "Low",
"exposureBasedRiskStatus": "Low",
"symptomBasedRiskStatus": "Low",
"riskMessage": "string",
"doYouHaveATemperature": true,
"temperature": 0,
"asessmentQuestion": [
{
"question": "string",
"answer": "string",
"createdBy": "string"
},
{
"question": "string",
"answer": "string",
"createdBy": "string"
},
{
"question": "string",
"answer": "string",
"createdBy": "string"
},
{
"question": "string",
"answer": "string",
"createdBy": "string"
},
{
"question": "string",
"answer": "string",
"createdBy": "string"
}
]
}
the object "asessmentQuestion" is an array of different questions, can't seem to figure out how to convert this structure to a swift dictionary or another recommended format for me to be able to post my data. My API is always saying bad request and I'm pretty sure I am not correctly mapping the json data.
this is a snippet of how I am attempting to map my json data:
var dictionary = [String:Any]()
dictionary["1. How old are you?"] = model.riskExposureBasedAssessment[0].answer
dictionary["2. Have you ever visited a COVID affected country?"] = model.riskExposureBasedAssessment[1].answer
dictionary["3. do you frequently experience flu like symptoms?"] = model.riskExposureBasedAssessment[2].answer
dictionary["4. Where you providing care in a non-health setting for a person with symptomatic COVID-19 infection"] = model.riskExposureBasedAssessment[3].answer
dictionary["5. Did you come in close contact* with a person with symptomatic laboratory-confirmed COVID-19 infection?"] = model.riskExposureBasedAssessment[4].answer
let parameters = [
"idNo": model.id,
"name": model.name,
"isRegistered": model.isRegistered,
"customMessage": model.customResponse,
"riskStatus": model.riskStatus,
"exposureBasedRiskStatus": model.exposureBasedRiskStatus,
"symptomBasedRiskStatus": model.symptomBasedRiskStatus,
"riskMessage": model.riskMessage,
"doYouHaveATemperature": model.doYouHaveATemperature,
"temperature": model.temperature,
"exposureBasedAssessments": dictionary
] as [String:Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters)
It's an array of dictionary, so :
var dictionaries: [[String: Any]] = []
// Populate dictionaries
// ...
let parameters = [
"idNo": model.id,
"name": model.name,
"isRegistered": model.isRegistered,
"customMessage": model.customResponse,
"riskStatus": model.riskStatus,
"exposureBasedRiskStatus": model.exposureBasedRiskStatus,
"symptomBasedRiskStatus": model.symptomBasedRiskStatus,
"riskMessage": model.riskMessage,
"doYouHaveATemperature": model.doYouHaveATemperature,
"temperature": model.temperature,
"exposureBasedAssessments": dictionaries
] as [String:Any]
Then, to populate it:
var dict1: [String: Any] = [:]
dict1["question"] = "1. How old are you?"
dict1["answer"] = model.riskExposureBasedAssessment[0].answer
dictionaries.append(dict1)
var dict2: [String: Any] = [:]
dict2["question"] = "2. Have you ever visited a COVID affected country?"
dict2["answer"] = model.riskExposureBasedAssessment[1].answer
dictionaries.append(dict2)
...
or
var dict1: [String: Any] = ["question": "1. How old are you?",
"answer": model.riskExposureBasedAssessment[0].answer]
dictionaries.append(dict1)
var dict2: [String: Any] = ["question": "2. Have you ever visited a COVID affected country?"",
"answer": model.riskExposureBasedAssessment[1].answer]
dictionaries.append(dict2)
...
But, I guess you have can retrieve the question from model.riskExposureBasedAssessment[n],
Instead of "1. How old are you?", can't you do model.riskExposureBasedAssessment[0].question?
If that's the case, you can use a for loop:
so I'd go with:
for aQuestionModel in model.riskExposureBasedAssessment {
let questionDict = ["question": aQuestionModel.question,
"answer": aQuestionModel.answer]
dictionaries.append(questionDict)
}
Or, once you master basic algorithm, closures, and map():
var dictionaries = model.riskExposureBasedAssessment.map { ["question": $0.question, "answer": $0.answer] }
It's missing the "createdBy", I don't know where to find it and if it's optional, but I think you should be able to add it if needed.
NotaBene:
Code not tested against a compiler. It should work, at maybe one or two typos.
I've local json file, which contains array of dictionaries. I want to group based on key name from below json. Means same name in one group. Please tell me how can I achieve that. Thank you.
Json Data:
[
{
"name": "Abc",
"number": 123,
"marks": 78
},
{
"name": "xyz",
"number": 456,
"marks": 50
},
{
"name": "Abc",
"number": 789,
"marks": 78
}
]
Code:
code and error message
init(grouping:by:)
You should return value of name key in the closure.
let arr = [ [ "name": "Abc", "number": 123, "marks": 78 ], [ "name": "xyz", "number": 456, "marks": 50 ], [ "name": "Abc", "number": 789, "marks": 78 ] ]
let dict = Dictionary(grouping: arr) { $0["name"] as! String }
print(dict)
//["Abc": [["name": "Abc", "number": 123, "marks": 78], ["name": "Abc", "number": 789, "marks": 78]], "xyz": [["name": "xyz", "number": 456, "marks": 50]]]
I am using the NiFi (v1.2) processor ConvertJSONToAvro. I am not able to parse a record that only contains 1 of 2 elements in a "record" type. This element is also allowed to be missing entirely from the data. Is my Avro schema incorrect?
Schema snippet:
"name": "personname",
"type": [
"null":,
{
"type": "record",
"name": "firstandorlast",
"fields": [
{
"name": "first",
"type": [
"null",
"string"
]
},
{
"name": "last",
"type": [
"null",
"string"
]
}
]
}
]
If "personname" contains both "first" and "last" it works, but if it only contains one of the elements, it fails with the error: Cannot convert field personname: cannot resolve union:
{ "last":"Smith" }
not in
"type": [ "null":,
{
"type": "record",
"name": "firstandorlast",
"fields": [
{
"name": "first",
"type": [
"null",
"string"
]
},
{
"name": "last",
"type": [
"null",
"string"
]
}
]
}
]
You are missing the default value
https://avro.apache.org/docs/1.8.1/spec.html#schema_record
Your schema should looks like
"name": "personname",
"type": [
"null":,
{
"type": "record",
"name": "firstandorlast",
"fields": [
{
"name": "first",
"type": [
"null",
"string"
],
"default": "null"
},
{
"name": "last",
"type": [
"null",
"string"
],
"default": "null"
}
]
}
]
Here is the request format that server requires ,
{
"internal_name": "SDSSD",
"display_name": "SDSDSDSD",
"image": "sesse.jpg",
"notes": "sdsdsdsdsdsdsdsd",
"short_description": "ssdsdsd",
"long_description": "sdsdsdsd",
"ean_code": "3434343434",
"status": "not_verified",
"state": "active",
"quantity": 1,
"brand": {
“name”: “My Brand”
},
"categories": [
{
“id”: “My Category”
}
]
}
In here , as you can see , it requires , categories as an array , so my question is how can i create an array . using swift . here is my swift code
let parameters :[String:AnyObject] = [
"internal_name":product.displayName,
"display_name":product.displayName,
"language":Constant.Language.LAN_ENGLISH,
"notes":product.initialName,
"image": product.photo,
"short_description":product.longDescription,
"long_description":product.longDescription,
"ean_code":product.eanCode,
"status":product.status,
"state":Constant.Status.STATUS_ACTIVE,
"categories": [
"id":product.categoryObject.id
],
"quantity":1,
]
this doesnt accept from the server since its not an array , what am i missing here
Try below code :
let parameters :Parameters = [
"internal_name":product.displayName,
"display_name":product.displayName,
"language":Constant.Language.LAN_ENGLISH,
"notes":product.initialName,
"image": product.photo,
"short_description":product.longDescription,
"long_description":product.longDescription,
"ean_code":product.eanCode,
"status":product.status,
"state":Constant.Status.STATUS_ACTIVE,
"brand" : ["name" : "My Brand"],
"categories": [
["id":product.categoryObject.id]
],
"quantity":1,
]
I need your help. I did an array, and when I launch my application on different devices or simulator, this array sorted into different types, but I need the same order on each device. How to do that?
var settings = [String: [ [String: String] ]]()
settings = [ "cards":[ ], "groups":[ ] ]
...
for card in db.prepare(table.order(orderN.asc)) {
settings["cards"]?.append(["id":String(card[id]), "group_id":String(card[group_id]), "service":card[service], "bgcolor":card[bgcolor], "logoimg":card[logoimg]!, "balance_desc":card[balance_desc], "balance":"0.0", "balance_id":String(card[balance_id]), "uniqueID":card[uniqueID], "balance_currency":String(card[balance_currency]), "orderN":String(card[orderN])])
}
...
for group in db.prepare(table.order(orderN.asc)) {
settings["groups"]?.append(["name":group[name]!,"id":String(group[id]),"orderN":String(group[orderN])])
}
...
For example,
On the first device
print(settings) // ["cards": [["orderN": "0", "bgcolor": "0.0, 0.0, 0.0, 1.0", "balance": "0.0", "logoimg": "example.com/images/img.png", "uniqueID": "00a2413f74f4a3f186e439a67057de67", "group_id": "2", "id": "1", "service": "servicename", "balance_desc": "Description", "balance_id": "1", "balance_currency": "1"]], "groups": [["orderN": "0", "name": "GroupName", "id": "2"]]]
On the second device
print(settings) // ["cards": [["orderN": "0", "uniqueID": "00a2413f74f4a3f186e439a67057de67", "service": "servicename", "id": "1", "bgcolor": "0.0, 0.0, 0.0, 1.0", "balance_currency": "1", "balance": "0.0", "group_id": "2", "logoimg": "example.com/images/img.png", "balance_id": "1", "balance_desc": "Description"]], "groups": [["id": "2", "orderN": "0", "name": "GroupName"]]]
Thank you for you attention.
That's because settings is not an Array, it's Dictionary. Order of key-value pairs in dictionary is not defined.
If you need some particular order, you should reimplement settings, probably make them separate struct or class, because you'll have a hard time working with nested dictionaries.