SwiftyJson get value from array in dictionary - ios

I've been trying to retrieve the value of code for a while now. This is the json I'm getting back from the server:
{
"message": "The given data was invalid.",
"errors": {
"code": [
"The code has already been taken."
]
}
}
How do I get the value of "code" with swiftyJson?
I've already tried this but I don't think it's correct.
let list: Dictionary<String, JSON> = json["errors"].dictionaryValue
var retunValue = list.values.first

You can access the first element of the "code" array like this:
json["errors"]["code"].array?.first?.string
This will give you nil if code were an empty array, or the JSON isn't the expected structure.
Since "code" is an array, it might contain more than 1 string, so you might want a [String] instead:
json["errors"]["code"].array?.compactMap { $0.string } ?? []
This will give you an empty array if the JSON is not the expected structure.

Related

iOS Swift How to get value of any key from json response

I am getting a response from an API
["response": {
record = {
title = "Order Add";
usercart = 5345;
};
}, "status": success, "message": تم إضافة السجل بنجاح]
I got the Value for status Key from the code
let statusCode = json["status"].string
Now i want the value for the key usercart in string value
I am using this code but getting any response.
let order_id = json["response"]["record"]["usercart"].string
Please help me to get this value.
As you are using SwiftyJSON and you are trying to get usercart value as a string but the usercart is Int.
So if you want this in string formate you should need to use .stringValue instead of .string else you can use .int or .intValue in form of int.
json["response"]["record"]["usercart"].stringValue
The json you are getting from server is wrong. Instead it should be -
["response": {
"record" : {
"title" : "Order Add",
"usercart" : 5345
};
}, "status": success, "message": تم إضافة السجل بنجاح]
There is nothing like = in json
Also if server response cannot change I would suggest reading this whole thing as string and then using search in string, though it is very bad approach.
if you are using SwiftyJSON then use this to get value
json["response"]["record"]["usercart"].stringValue

How to correctly send array with objects in JSON Swift iOS

Hello I am beginner and trying to understand how to send an array with objects. Does the server understand what an array is like Int, Strings or Booleans? Do you have to send the array in a string for JSON? What I do not understand?
var productsResult = ""
let encoder = JSONEncoder()
let productObject = ProductUsed(name: "Custom name", reason: "This Reason", apply_way: "Intravenous infusion", dosing: "2x", date_start: "22-02-1999", date_end: "22-03-2003")
do {
let result = try encoder.encode([productObject])
if let resultString = String(data: result, encoding: .utf8) {
print(resultString)
productsResult = resultString
}
} catch {
print(error)
}
json["products_used"] = productsResult
And I sent to server with parameters like this:
parameters: ["pregnancy_week": 0, "body_height": 198, "initials": "John Appleseed", "heavy_effect": false, "sex": "Male", "pregnancy": false, "month_of_birth": 3, "reaction": "No option checked", "additional_info": "Eeee", "products_used": "[{\"date_end\":\"22-03-2003\",\"dosing\":\"2x\",\"date_start\":\"22-02-1999\",\"apply_way\":\"Intravenous infusion\",\"name\":\"Custom name\",\"reason\":\"This Reason\"}]", "description": "Eeee", "result": "Recovery without lasting consequences", "year_of_birth": 1983, "day_of_birth": 11, "issue_date": "15-11-2020", "body_weight": 78]
but printed "resultString" in log and looks good...
[{"date_end":"22-03-2003","dosing":"2x","date_start":"22-02-1999","apply_way":"Intravenous infusion","name":"Custom name","reason":"This Reason"}]
What's wrong in my code and why I have " \ " between words in "products_used" key?
JSON, unlike XML, does not specify the structure and type explicitly. This means that the server must know what JSON data to expect.
In JSON there are a few value types (https://www.w3schools.com/js/js_json_syntax.asp):
a string
a number
an array
a boolean
null
a JSON object (a dictionary with tags like { "first" : "John", "last" : "Doe" }). This allows nesting.
A JSON object is a set of tag-value pairs. The tag and value are separated by : and pairs are separated by ,.
An array is a list of JSON values. So for example [ "hello", world" ] is a JSON array with 2 strings and [ 12, 54 ] is a JSON array with two numbers.
Your parameter list ["pregnancy_week": 0, "body_height": 198, ... is not an array but a dictionary instead. A Swift dictionary is translated to an JSON object, not a JSON array.
The \ you see printed acts as escape character. This escape character is used to allow you to have a " inside the string.
That's just a few things that I hope will help understand things a bit better. Your questions are pretty basic, which is fine and it's great you want to understand things. But instead of us explaining everything here, I think it would be best if you'd read about the structure of JSON and how JSON works in Swift on your own.

Parsing json data using swift json

I can’t get the JSON data of message using swiftyjson.
When i print JSON value is there. But, when i print(json["result"]["message"]) it is null
{
"result": [{
"message": "success",
"age": "25"
}]
}
let json = JSON(data:jdata)
print(json)
print(json["result"]["message"])
json["result"] seems to be an array, you have to cast it to array like
let array = json["result"].arrayValue
let message = array[0]["message"]
You result is of array type. And you have to set index of object.
Try:
var array = json["result"].arrayValue
print(array[0]["message"])
You can also check this question
Hope it helps
Try:
let json = JSON(data: jdata)
let message = json["result"].array?.first?["message"]
print(message)

SwiftyJSON add array of JSON objects

I am trying to serialize my object graph into JSON using the SwiftyJSON Library. I have a function in a BirthdayEvent class named "toJSON" which converts individual Birthday Events into swiftyJSON objects successfully.
However I am keen to have something like the following structure to the JSON:
"birthdays" : [
{
"eventId": "...",
"date": "01/01/2000",
...
},
{
"eventId": "...",
"date": "01/02/2001",
...
},
...
]
I am finding it difficult to create a JSON dictionary with the String "birthday" as the key and the array of BirthdayEvent JSON items as the value.
I have the following code:
var birthdaysJSON: JSON = JSON(self.events.map { $0.toJSON() })
var jsonOutput : JSON = ["birthdays": birthdaysJSON]
The first line successfully creates a JSON object of the array of events, but I cannot seem to use this in the dictionary literal. I get an error of "Value of type 'JSON' does not conform to expected dictionary value type 'AnyObject'.
Can you tell me where I am going wrong, or am I over-complicating this?
To create a JSON dictionary, you have to initialize the JSON object on jsonOutput just like you did with birthdaysJSON:
var jsonOutput: JSON = JSON(["birthdays": birthdaysJSON])

How to push data with multiple types in Firebase?

I want to push an array that has strings, numbers and date. Do I have to update individually or is there another way I can accomplish this?
Example:
var categories : [String] = self.parseCategories()
var standbyDataStrings = [
"firstName":firstName,
"lastName":lastName,
"categories": categories,
"time_stamp":self.date.timeIntervalSince1970
]
var standbyDataNums = [
"radius":nf.numberFromString(self.helpRadiusLabel.text!),
"duration":nf.numberFromString(self.helpDurationLabel.text!)
]
standbyUserRef.updateChildValues(standbyDataStrings)
standbyUserRef.updateChildValues(standbyDataNums) // this gives me a error "string is not identical to NSObject"
Combining standByDataStrings and standbyDataNums gives me an error.
Or is there a way to retrieve a string from Firebase and using it as an int. It gets stored as a String with the quotations.
The Firebase API expects an NSDictionary for updateChildValues. A NSDictionary can't contain nil values. A normal Swift dictionary on the other hand can contain nil values.
The return type of numberFromString is NSNumber?, so Swift infers that the dictionary might contain nil and so it can't be passed to updateChildValues. By explicitly forcing non-nil values with ! you can make this code compile:
var standbyDataNums = [
"radius":nf.numberFromString(self.helpRadiusLabel.text!)!,
"duration":nf.numberFromString(self.helpDurationLabel.text!)!
]
standbyUserRef.updateChildValues(standbyDataNums) // now type checks

Resources