I am trying to create a dictionary in a static way and obtain the data, but I am not correct. I mean because it is only an array of string and any, but in the image it has brackets and braces. Any help I will appreciate a lot, thanks for your time
let responseDevice : [String : Any] = [
"date_s" : "2021-02-18",
"id_c" : "4",
"id_d" : 1,
"data" : [
"Peso" : 34,
"Fc" : -1,
"Age" : 34,
"Name" : "July"
],
"flags" : 0,
"error" : 0
]
if let date_s = responseDevice["date_s"] as? String,
let dat = responseDevice["data"] as? [String : Any],
let peso = dat["Peso"] as? Int {
print(date_s)
print(peso)
}
print("log :\(responseDevice)")
result:
2021-02-18
34
log :["id_c": "4", "error": 0, "id_d": 1, "flags": 0, "date_s": "2021-02-18", "data": ["Peso": 34, "Fc": -1, "Age": 34, "Name": "July"]]
What you created is a Swift Dictionary. What you have on that image is JSON Object. It's not very clear what your goal is, so couple of basic pointers:
If you want to parse JSON into Dictionary, check this answer
If you simply want to include some JSON sample in your code (e.g. for testing), you can put it in triple quotes:
var myJSON = """
[paste your JSON here]
"""
Related
sorry, I'm trying to add a json of type dictionary and get the values. I don't know if I'm doing it correctly, that's how it works for me, but when I get the values of the function that the dictionary returns, my application doesn't get anything.
I tried to obtain this data in different ways. I don't know if someone could give me any idea, thank you.
let jsonLifevitPBM_200 = """
{
"result" : [
{
"id_d" : 55,
"id_c" : "0",
"data" : [
{
"Diastolic" : 85,
"ErrorCode" : -1,
"Systolic" : 120,
"Pulse" : 72
}
],
"date_s" : "2021-07-28 09:45:16.201"
}
],
"error" : 0,
"flags" : 0
}
"""
let jsonKelvin = Data(jsonLifevitPBM_200.utf8)
let jsonKelvinResult = try? JSONDecoder().decode(VitalSignTermometreResponse.self, from: jsonKelvin)
let temperature = jsonKelvinResult?.result[0].data[0].Temperature
let mode = jsonKelvinResult?.result[0].data[0].Mode
let unit = jsonKelvinResult?.result[0].data[0].Unit
if let tem = temperature , let mod = mode , let uni = unit {
labelsystole.text = "Error: \(tem)"
labeldiastole.text = "Error: \(mod)"
labelPulse.text = "Error: \(uni)"
} else {
labelResult.text = "Error Medisana BU 575 Connect"
}
Another way of trying to create the dictionary and get the data was this way, but I don't think it is in the correct way
let responseDevice : [String : Any] = [
"result" : [
"id_d" : 55,
"id_c" : "0",
"data" : [
"Diastolic" : 85,
"ErrorCode" : -1,
"Systolic" : 120,
"Pulse" : 72
],
"date_s" : "2021-07-28 09:45:16.201"
]
]
if let dat = responseDevice["result"] as? [String : Any] {
if let resultData = dat["data"] as? [String : Any] {
if let diast = resultData["Diastolic"] as? String ,
let systolic = resultData["Systolic"] as? String {
println("Result : \(diast) - \(systolic)")
}
}
}
I think the best way to do that is to use a third party library to get JSON and after that you can manage JSON values.
https://github.com/SwiftyJSON/SwiftyJSON
Hi i am trying to give to alamofire parameters called "addons" that are in array...array can contain 3 or X items. I am trying to use FOR cycle to ad dictionary to another another one set of items, but...it only shows the last one...that seems it override the previous one. I tried everything I know...Even try to use SwiftyJSON framework....but alamofire only take pure dictionary type.
let itemsArr = ["Skirts", "Coat", "Shirt"]
let priceArr = ["7.00", "7.00", "2.90"]
let quantityArr = ["2", "5", "1"]
let personalInfo: [String : Any] = [
"phone" : phone,
"notes" : descNote
]
var para: [String: Any] = [
"pieces" : pieces,
"personal_info" : personalInfo,
"payment_method" : paymentMethod
]
for i in 0..<itemsArr.count {
let addons: [String: Any] = [
"name":itemsArr[i],
"price":priceArr[i],
"quantity":quantityArr[i]
]
print(addons)
para["addons"] = addons
}
well I need something like this
{
"pieces": 12,
"personal_info": {
"phone": "+420783199102",
"notes": "Plz be fast, I need to play Game of War"
},
"payment_method": "cod",
"addons": [
{
"name": "Select day Tue",
"price": 3.5,
"quantity": 1
},
{
"name": "Select day Thu",
"price": 3.5,
"quantity": 1
}
]
}
Your problem is that in loop you are overwriting variable every single iteration with single result. That's why only last one is left for you.
What you should do is:
//create an array to store the addons outside of the loop
var addons: [[String: Any]] = []
for i in 0..<itemsArr.count {
let addon: [String: Any] = [
"name":itemsArr[i],
"price":priceArr[i],
"quantity":quantityArr[i]
]
//append a single addon to our array prepared before the loop
addons.append(addon)
}
//once we gathered all addons, append results to `para` dictionary
para["addons"] = addons
I am trying to create a dictionary that I can make into a JSON formatted object and send to the server.
Example:
var users = [
[
"First": "Albert",
"Last": "Einstein",
"Address":[
"Street": "112 Mercer Street",
"City": "Princeton"]
],
[
"First": "Marie",
"Last": "Curie",
"Address":[
"Street": "108 boulevard Kellermann",
"City": "Paris"]]
]
I use this function
func nsobjectToJSON(swiftObject: NSObject) -> NSString {
var jsonCreationError: NSError?
let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(swiftObject, options: NSJSONWritingOptions.PrettyPrinted, error: &jsonCreationError)!
var strJSON = NSString()
if jsonCreationError != nil {
println("Errors: \(jsonCreationError)")
}
else {
// everything is fine and we have our json stored as an NSData object. We can convert into NSString
strJSON = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
println("\(strJSON)")
}
return strJSON
}
But my result is this:
[
{
"First" : "Albert",
"Address" : {
"Street" : "112 Mercer Street",
"City" : "Princeton"
},
"Last" : "Einstein"
},
{
"First" : "Marie",
"Address" : {
"Street" : "108 boulevard Kellermann",
"City" : "Paris"
},
"Last" : "Curie"
}
]
Problem: why is the last name last? I think it should be above address. Please let me know what I am doing wrong with the NSDictionary for this to come out wrong. Any help would be very much appreciated - thank you.
To post what has already been said in comments: Dictionaries are "unordered collections". They do not have any order at all to their key/value pairs. Period.
If you want an ordered collection, use something other than a dictionary. (an array of single-item dictionaries is one way to do it.) You can also write code that loads a dictionary's keys into a mutable array, sorts the array, then uses the sorted array of keys to fetch key/value pairs in the desired order.
You could also create your own collection type that uses strings as indexes and keeps the items in sorted order. Swift makes that straightforward, although it would be computationally expensive.
I did like this.
let stagesDict = NSDictionary()
if let strVal = sleepItemDict["stages"] as? NSDictionary {
stagesDict = strVal
let sortedKeys = (stagesDict.allKeys as! [String]).sorted(by: <)
var sortedValues : [Int] = []
for key in sortedKeys {
let value = stagesDict[key]!
print("\(key): \(value)")
sortedValues.append(value as! Int)
}
}
I'm having a bit of trouble structuring my parameters so that our server API would be able to read it as valid JSON.
Alamofire uses parameters like this in swift language
let parameters : [String: AnyObject] =
[
"string": str
"params": HOW I INSERT A VALID JSON ARRAY HERE
]
The problem is that AnyObject does not seem to accept JSON so how would I send / create a structure like this with swift?
{
"string": str, "params" : [
{
"param1" : "something",
"param2" : 1,
"param3" : 2,
"param" : false
},
{
"param1" : "something",
"param2" : 1,
"param3" : 2,
"param" : false
}]
}
Taken from Alamofire's GitHub page:
let parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
EDIT: And from your example:
let parameters = [
"string": "str",
"params": [[
"param1" : "something",
"param2" : 1,
"param3" : 2,
"param" : false
],[
"param1" : "something",
"param2" : 1,
"param3" : 2,
"param" : false
]
]
]
Solved this myself. I can just do
parameters =
[
"params": array
]
Where array is Dictionary (String, AnyObject). The problem I initially had with this solution was that you can't insert booleans into this kind of dictionary, they will just be converted into integers. But apparently alamofire JSON encoding (I think) sends them as true/false values nevertheless.
In case, there is a need to pass array directly as a parameter for a alamofire request, the following method worked for me.
source: https://github.com/Alamofire/Alamofire/issues/1508
let headers = NetworkManager.sharedInstance.headers
var urlRequest = URLRequest(url: URL(string: (ServerURL + Api))!)
urlRequest.httpMethod = "post"
urlRequest.allHTTPHeaderFields = headers
let jsonArrayencoding = JSONDocumentArrayEncoding(array: documents)
let jsonAryEncodedRequest = try? jsonArrayencoding.encode(urlRequest, with: nil)
var request: Alamofire.DataRequest? = customAlamofireManager.request(jsonAryEncodedRequest!)
request?.validate{request, response, data in
return .success
}
.responseJSON {
You need to create a NSArray object for array parameters.
var yourParameters = [
"String": "a string",
"Int": 1,
"Array": NSArray(
array: [
"a", "b", "c"
])
]
Swift 2.2 and using SwiftyJSON.swift
You can use like this.
var arrayList : [String: AnyObject]//one item of array
var list: [JSON] = []//data array
for i in 0..<10//loop if you need
{
arrayList = [
"param1":"",
"param1":"",
"param2":["","",""]
]
list.append(JSON(arrayList))//append to your list
}
//params
let params: [String : AnyObject]=[
"Id":"3456291",
"List":"\(list)"//set
]
if you are using SwiftyJSON, you can write like this
let array = ["2010-12-13T5:03:20","2010-12-13T5:03:20"]
let paramsJSON = JSON(array)
var arrString = paramsJSON.rawString(NSUTF8StringEncoding)
Using Swift 5
You can use like this.
var authParams:[String:Any] = [:]
var authParamsObject:[String:Any] = [:]
authParamsObject["is_urgent"] = data_any
authParamsObject["body"] = data_any
authParams = ["note_set" : authParamsObject]
Json Result :
{
"note_set":
{
"is_urgent": true,
"body": "string"
}
}
I've a NSDictionary populated by a JSON file.
JSON file content (initially)
{
"length" : 0,
"locations" : []
}
I want add some elements in "locations". The elements have the below structure:
[
"name" : "some_name",
"lat" : "4.88889",
"long" : "5.456789",
"date" : "19/01/2015"
]
In next code I read de JSON File
let contentFile = NSData(contentsOfFile: pathToTheFile)
let jsonDict = NSJSONSerialization.JSONObjectWithData(contentFile!, options: nil, error: &writeError) as NSDictionary`
like you can see jsonDict contain the JSON's info but in a NSDictionary object.
At this point I can't add the elements mentioned before, I tried insert NSData, NSArray, Strings, and nothing results for me
After do this I want convert "final" NSDictionary in JSON again to save it in a file.
The "final" NSDictionary must be like this
{
"length" : 3,
"locations" : [
{
"name" : "some_name",
"lat" : "4.88889",
"long" : "5.456789",
"date" : "19/01/2015"
},
{
"name" : "some_name_2",
"lat" : "8.88889",
"long" : "9.456789",
"date" : "19/01/2015"
},
{
"name" : "some_name_3",
"lat" : "67.88889",
"long" : "5.456789",
"date" : "19/01/2015"
}
]
}
"length" control the index for new element
I have no more ideas to do this. thanks in advance
If you want to be able to modify the dictionary, you can make it mutable:
let jsonDict = NSJSONSerialization.JSONObjectWithData(contentFile!, options: .MutableContainers, error: &writeError) as NSMutableDictionary
The resulting NSMutableDictionary can be modified. For example:
let originalJSON = "{\"length\" : 0,\"locations\" : []}"
let data = originalJSON.dataUsingEncoding(NSUTF8StringEncoding)
var parseError: NSError?
let locationDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers, error: &parseError) as NSMutableDictionary
locationDictionary["length"] = 1 // change the `length` value
let location1 = [ // create dictionary that we'll insert
"name" : "some_name",
"lat" : "4.88889",
"long" : "5.456789",
"date" : "19/01/2015"
]
if let locations = locationDictionary["locations"] as? NSMutableArray {
locations.addObject(location1) // add the location to the array of locations
}
If you now constructed JSON from the updated locationDictionary, it would look like:
{
"length" : 1,
"locations" : [
{
"long" : "5.456789",
"lat" : "4.88889",
"date" : "19/01/2015",
"name" : "some_name"
}
]
}