I am able to get the entire JSon array parsed. It outputs to console with no issue. I can't seem to get the individual params from the array... my json looks like:
[{
City = NYC;
Device = "<null>";
DisplayAs = "Steve Hutson";
FirstName = Steve;
LastName = Hutson;
MobilePhone = "000-000-0000";
Org = "<null>";
Region = "";
Role = INSPECTOR;
SupervisorID = "73990";
email = "email#email.com";
fLast = shutson;
"gz_modtimestamp" = "2015-07-28 14:42:41";
id = 96;
isActive = YES;
lastupdated = "<null>";
sendemail = 1;
token = "<null>";
userpassword = "xxx";
},{
City = DET;
Device = "<null>";
DisplayAs = "Filipe Washington";
FirstName = Filipe;
LastName = Washington;
MobilePhone = "000-000-0000";
Org = "<null>";
Region = "";
Role = INSPECTOR;
SupervisorID = "6567";
email = "email#email.com";
fLast = shutson;
"gz_modtimestamp" = "2015-07-28 13:02:09";
id = 93;
isActive = YES;
lastupdated = "<null>";
sendemail = 1;
token = "<null>";
userpassword = "xxx";
}]
In my main ViewController.swift file my json request looks like:
var myData:NSData = getJSON("http://xxxx/getusersData.php")
var myDict:NSArray = parseJSON(myData)
println(myDict)
This prints my entire json object which is perfect. However my issue is, how do I get only the FirstName's in an array? By index this works:
println(myDict[0]["FirstName"]) how ever, it only brings back one item.
I am trying to insert specific json items into sqlite which i am using SQLite.swift but i need to know how to retrieve specific item parameters as I would if i was using AJAX.
I am trying to retrieve FirstName, Email and UserPassword info.
Any help would be appreciated.
You can iterate over the JSON object and retrieve that info:
for (index: String, subJson: JSON) in json {
//Do something you want
var firstName = subJson["FirstName"].stringValue
var email = subJson["email"].stringValue
var userPassword = subJson["userpassword"].stringValue
// Build the sqlite query with the variables here
}
As a clarification, you don't access the values directly as in json["FirstName"], you must also use the type functions from SwiftyJSON. In your case they're both strings, so stringValue is used. If you needed and int, it'd be intValue.
There's also the option of just json["FirstName"].string in case the field is optional. Take a look at the readme
Related
I am calculating hash from server and passed it to payUbiz hash object. When hash value passed to hash object of payUbiz it binds as optional value i.e. Optional(*hashValue*). I have tried to convert optional string to string, but it won't worked. It gives Invalid Parameter error.
Below is my hash value response from server:
{
errorMessage = "Success.";
lastSyncDateTime = "<null>";
result = {
furl = "http://192.168.3.2:93/PayU/AppointmentResponse";
hash = 4875a6096814ee1fbe19110582ea0a1564f81880ae66539b94384d3d332106855a00132332919724f085d02d64cffb6d47ff98f3ac4eb7d5e2bb31b4022e3f06;
merchantKey = gtKFFx;
mobileSDKHASH = 110f85b862578214e5c38637762a6fce9c34bd5e2d78bc34a486f0ee2e3e5d0fada221795de4b67952ec2cff6b4d0fe8877506e7a5480bbdbfdf9045521d8523;
payURequestArea = 1;
profileID = 7;
surl = "http://192.168.3.2:93/PayU/AppointmentResponse";
txnID = 62604613a06163c02ddd;
userID = 18;
vasMobileSDKHASH = 7da0f4fef5bab0e5034f37f9503bdcbede00cc2cd0cf6cbb4e43baa9d57f05680305885199e2b0d38e8cf12895fd06f4d3dd3fb422535feeb555adc58e2cf3cc;
};
statusCode = 200;
}
This is hashvalue printed from payUbiz
paymentHash: Optional("4875a6096814ee1fbe19110582ea0a1564f81880ae66539b94384d3d332106855a00132332919724f085d02d64cffb6d47ff98f3ac4eb7d5e2bb31b4022e3f06")
vasForMobileSDKHash: Optional("7da0f4fef5bab0e5034f37f9503bdcbede00cc2cd0cf6cbb4e43baa9d57f05680305885199e2b0d38e8cf12895fd06f4d3dd3fb422535feeb555adc58e2cf3cc")
paymentRelatedDetailsHash: Optional("110f85b862578214e5c38637762a6fce9c34bd5e2d78bc34a486f0ee2e3e5d0fada221795de4b67952ec2cff6b4d0fe8877506e7a5480bbdbfdf9045521d8523")
Please give solution on this
I have faced same issue a month ago. I think Optional value is not cause of issue. The response itself say's that "Invalid Parameters" means there are some invalid parameters passed to Payment gateway.
Please check following parameters are provided or not:
paymentParam.key = *Your key*;
paymentParam.transactionID = *Transaction ID*
paymentParam.amount = *Amount*
paymentParam.productInfo = *Product Info*;
paymentParam.surl = *Success URL*;
paymentParam.furl = *Failure URL*;
paymentParam.firstName = "";
paymentParam.email = "";
paymentParam.udf1 = "";
paymentParam.udf2 = "";
paymentParam.udf3 = "";
paymentParam.udf4 = "";
paymentParam.udf5 = "";
paymentParam.hashes = hashes; //**Important**
paymentParam.userCredentials = "default"; **//This was the issue in my case, i have accidentally deleted this parameter**
// ENVIRONMENT_TEST for test environment:
paymentParam.environment = ENVIRONMENT_TEST;
// Set this property if you want to give offer:
paymentParam.offerKey = "";
Please check for paymentParam.userCredentials = "default" parameter,
because after adding this parameter i have solved my issue.
Hope this will help you.
Good Day.
I have a iOS Swift Application that communicates with a companies already created API and its communicated with using Alamofire. The problem I have is the API can possibly return nulls some time and this causes the following problem:
"fatal error: unexpectedly found nil while unwrapping an Optional value"
My code snippet that reads from the dictionary is as follows:
if let LowRate = HotelList[i]["LowRate"] as? Decimal!{
HList._LowRate = LowRate
}
I have reviewed multiple questions and google sites however I need a way to check the object in the dictionary for null before its processed or I need to set some type of default value.
The Json null example is as follows
HotelData = "<null>";
HotelList =(
{
Address1 = "124 Oceanview Road";
Address2 = Oneroa;
BookingUrl = "<null>";
City = " Auckland";
Country = "New Zealand";
CurrencyCode = "<null>";
DateViewed = "<null>";
Description = "<null>";
Directions = "<null>";
Distance = "<null>";
GeoPoint = "<null>";
HighRate = "<null>";
ImageUrl = "<null>";
LowRate = "<null>";
MinChildAge = "<null>";
Name = "The Oyster Inn";
NavUrl = "<null>";
PostalCode = "<null>";
State = "<null>";
WebsiteUrl = "<null>";
distance = "<null>";
hotelID = 130;
isActive = 1;
isBlocked = 0;
isChildrenAllowed = "<null>";
isFavorite = 0;
isPromoNotified = 0;
showDouble = "<null>";
}
);
RowCount = 11;
hasError = 0;
};
I am using Alamofire for my json and it works unless there is a null returned in one of the 20 fields that could possibly return a null.
Can anyone assist me in doing some validation checks for the result of a null as shown above while unwrapping an optional.
Regards
This is how you can do this.(Updated)
if let lowRate = json["LowRate"], !(lowRate is NSNull){
print(lowRate)
}else{
print("null")
}
Good Day
Thanks to all the contributions to helping me find my answer. What worked in the end was something very similar to above I had to use a NSNumber object and then cast it to a decimal later along the lines please see code below.
if let lowRate = HotelList[i]["LowRate"] as? NSNumber{
HList._LowRate = LowRate
}else{
print("Null")
}
Regards
Your json has array of only one object. What is the value of i? If it's greater than 0 it will crash.
I'm running into what I believe to be a bug. I have an array of objects returned from a server. However, when pulling values out of them I get inconsistent results. Each of these items are in the same array of the response from server:
When I try to pull the quantity value of this one it returns as in Int:
{
address = "4040 MARKET ST RM 226";
city = PHILADELPHIA;
ln = "AMOXICILLIN 500 MG CAPSULE";
ndc = 57237003105;
npi = 1619912375;
"pharmacy_name" = "GRACE PHARMACY INC";
phone = "(215)895-5594";
price = "8.00";
quantity = 500;
state = PA;
vendor = una;
zip = 19104;
}
However, when I try to pull quantity from this one, it's returned as a String.
{
address = "1826 Chestnut St # 30";
brand = G;
city = Philadelphia;
distance = "0.06";
latitude = "39.951747";
ln = "AMOXICILLIN 500 MG CAPSULE";
longitude = "-75.171154";
"ncpdp_id" = 3969485;
ndc = 65862001705;
"pharmacy_hours_of_operation" = "Open 24 Hours";
"pharmacy_name" = "CVS PHARMACY";
phone = "(215)972-0909";
price = "11.82";
quantity = 30;
state = PA;
vendor = scriptsave;
zip = "19103-4902";
}
Why in the world would this be occurring? Both objects seems to be identical except for some extra values in one.
===
Serializing the JSON like this:
let searchResultsJSON: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) as! NSDictionary
Grabbing the values like this:
quantity = formDictionary["quantity"] as? Int
quantityString = formDictionary["quantity"] as? String
====
Here is the JSON:
results = (
{
address = "4040 MARKET ST RM 226";
city = PHILADELPHIA;
ln = "ESOMEPRAZOLE MAG DR 40 MG CAP";
ndc = 13668015510;
npi = 1619912375;
"pharmacy_name" = "GRACE PHARMACY INC";
phone = "(215)895-5594";
price = "74.00";
quantity = 1000;
state = PA;
vendor = una;
zip = 19104;
},
{
address = "1700 Market St";
brand = G;
city = Philadelphia;
distance = "0.22";
latitude = "39.952981";
ln = "ESOMEPRAZOLE MAG DR 40 MG CAP";
longitude = "-75.168431";
"ncpdp_id" = 3985059;
ndc = 00378235193;
"pharmacy_hours_of_operation" = "S(Clsd) M(8a-6p) T(8a-6p) W(8a-6p) T(8a-6p) F(8a-6p) S(9a-12p)";
"pharmacy_name" = "PICKWICK PHARMACY INC";
phone = "(215)563-4860";
price = "241.23";
quantity = 30;
state = PA;
vendor = scriptsave;
zip = "19103-3913";
}
);
So here, quantity in the first one is returned as an Int and as a String in the second one. I beginning to think this is a server side issue...
===
Looking at the JSON in Chrome does confirm that it's an encoding error from the server. Thanks #CouchDeveloper
Apple's API's for JSONSerialization are a bit nasty for usage in Swift.
If your happy to make use of third-party frameworks, SwiftyJSON will help with handling JSON in a type safe manner in swift. It's available as a Cocoapod, using Carthage or even Swift's own package manager.
You can then ensure you get non-nil Integer or String objects like so:
let name = json["name"].stringValue
let number = json["number"].intValue
Or you can handle non-existent values as optionals like so:
let name = json["name"].string
let number = json["number"].int
I have an object that looks like this in the console. It seems like an array with a dictionary inside. How can I get to the address field?
Optional((
{
address = "xxxxxxx#gmail.com";
verified = 1;
}
))
The object comes from this object:
<METDocument key: <collection: users, ID: KTsCySacEAiz3eDnf>, fields: {
emails = (
{
address = "xxxxxxx#gmail.com";
verified = 1;
}
);
profile = {
address = {
city = Oslo;
country = nor;
lineOne = "address";
lineTwo = "";
zip = 0264;
};
birthdate = "1985-09-01 23:00:00 +0000";
card = {
last4 = 4242;
verified = 1;
};
filledOut = 1;
gender = Male;
name = {
first = "Elon";
last = "Musk";
};
phone = 911;
validated = 1;
};
}>
I access the emails key by this method:
let emails = users.allDocuments[0].valueForKey("emails")
The content of the object is an optional array.
There are two options:
Safe access:
if let emails = users.allDocuments[0].objectForKey("emails") where emails.count > 0 {
if let address = emails[0]["address"] as? String {
print(address)
}
}
If it's guaranteed that the dictionary in the array and the key address exists:
let emails = users.allDocuments[0].objectForKey("emails")!
let address = emails[0]["address"] as! String
I receive an object that is sent as a pointer to a collection.
I can access the fields directly as an NSDictionary.
The emails field is sent as an array, and I receive it in parentheses. Currently I get the emailaddress by what I feel is a roundabout method.
How can I most efficiently get to the email address?
let allDoc = users.allDocuments[0]
print("allDoc: \(allDoc)")
let emailsArray = users.allDocuments[0].valueForKey("emails") as! NSArray
print("emailsArray: \(emailsArray)")
let emailAddress = emailsArray[0]["address"] as! String
print("emailAddress: \(emailAddress)")
Console output:
allDoc: <METDocument key: <collection: users, ID: kzzw3vcqukD62xEyz>, fields: {
emails = (
{
address = "xxxx#gmail.com";
verified = 1;
}
);
profile = {
address = {
city = "";
country = nor;
lineOne = "";
lineTwo = "";
zip = "";
};
card = {
last4 = 4242;
verified = 1;
};
filledOut = 1;
name = {
first = XXXX;
last = XXXX;
};
phone = 9999999999;
validated = 1;
};
}>
emailsArray: (
{
address = "xxxx#gmail.com";
verified = 1;
}
)
emailAddress: xxxx#gmail.com
If you just want the email address you could simply do:
let emailsAddress = users.allDocuments[0]["emails"][0][#"address"] as! String
print("emailAddress: \(emailAddress)")
But it really is better to use multiple lines. It makes the code much easier to read and debug. Also, putting all that onto one line doesn't allow any error checking. What if the #"emails" key has an empty array, for example? The code will crash.