how can I get applicationStateJson in below code, I can parse the bellow JSON object from data but can not able to get applicationStateJson from it
{
applicationStateJson = {
"address_status" = 0;
email = "xxxxxxxx;
"email_status" = 0;
"first_name" = xxx;
"last_name" = "";
"login_status" = 1;
loginstype = "<null>";
mobile = xxxxxx;
"mobile_status" = 1;
notifications = (
);
"notifications_size" = 0;
"otp_status" = 3;
"profile_id" = "<null>";
"profile_name" = "virtual_recruiter";
"user_id" = 454;
"user_status" = 1;
"virtual_recruiter_id" =xxx;
};
"error_msg" = "<null>";
status = "<null>";
}
code as
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(json)
let applicationStateJson = try json["applicationStateJson"]
} catch { print(error.localizedDescription) }
Try with below code
First you need to change in below line, its Dictionary<String, Any> not an AnyObject
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, Any>
And then get applicationStateJson by below code
if let appJson = json["applicationStateJson"] as? Dictionary<String, Any> {
print(appJson)
print("Email : \(appJson["email"] as? String ?? "Email not found")") // For get email
}
The root object of the JSON is a clearly a dictionary, not AnyObject (an object but I-have-no-idea-what-it-is).
The value for key applicationStateJson is a dictionary, too.
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String:Any],
let applicationStateJson = json["applicationStateJson"] as? [String:Any] {
print(applicationStateJson)
}
} catch {
print(error)
}
As always, .mutableContainers is completely meaningless in Swift
Related
I'm trying to parse the response object from an API call, but having some difficulty.
First, I parsed the returned JSON with following:
let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
if let result = responseObject["result"] {
print(result)
}
Then, when I log the result, following is what I get:
{
"_links" = {
next = "/api/3/action/datastore_search?limit=50&id=22f223e7-73f7-4842-935c-80a0ba5c3e5b&offset=50";
start = "/api/3/action/datastore_search?limit=50&id=22f223e7-73f7-4842-935c-80a0ba5c3e5b";
};
fields = (
{
id = "_id";
type = int;
},
{
id = package;
info = {
label = "";
notes = "Unique, normalized, name of dataset.
"type_override" = "";
};
type = text;
}
)
}
I tried parsing it again:
let finalResult = (try? JSONSerialization.jsonObject(with: result)) as? [String: Any]
But, I get the following error:
No exact matches in call to class method 'jsonObject'
Update
if let result = responseObject["result"] as? [String: Any] {
if let finalResult = result["records"] {
print(finalResult)
}
}
When I log this, I get the following:
(
{
"_id" = 186;
accessibility = 1;
completeness = "0.6899999999999999";
freshness = "0.5";
grade = Silver;
"grade_norm" = Silver;
metadata = "0.84";
package = "air-conditioned-and-cool-spaces-heat-relief-network";
"recorded_at" = "2019-12-17T20:24:09";
score = "0.78";
"score_norm" = "0.76";
usability = "0.86";
version = "v0.1.0";
},
{
"_id" = 187;
accessibility = 1;
completeness = 1;
freshness = 0;
grade = Bronze;
"grade_norm" = Bronze;
metadata = "0.25";
package = "air-conditioned-public-places-cooling-centres";
"recorded_at" = "2019-12-17T20:24:09";
score = "0.54";
"score_norm" = "0.31";
usability = "0.85";
version = "v0.1.0";
},
)
When I tried to iterate this:
for (key, value) in finalResult {
print("key", key)
print("value", value)
}
I get the following error:
Tuple pattern cannot match values of none-tuple type
Thanks to #OOPer, I was able to parse it as a dictionary:
if let result = responseObject["result"] as? [String: Any] {
if let finalResult = result["records"] as? [[String: Any]] {
finalResult.forEach { (catalogue) in
if let package = catalogue["package"] as? String {
}
}
}
}
I have an array being returned in Xcode which outputs the following:
["userDetails": {
id = 31;
"user_email" = "steve#gmail.com";
"user_name" = "Steve Downs";
}, "communities": <__NSArrayI 0x600000245f40>(
{
id = 5;
name = South;
},
{
id = 13;
name = HurraHarry;
},
{
id = 15;
name = EnclliffeT;
}
)
]
The code below correctly assigns the values contained within "communities" to their respective variables.
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json!)
if let arr = json?["communities"] as? [[String:String]] {
self.communitiesArray = arr.flatMap { $0["name"]!}
self.communityIdsArray = arr.flatMap { $0["id"]!}
}
if let arr = json?["userDetails"] as? [AnyObject] {
self.playerId = (arr.flatMap { $0["id"]!} as (AnyObject)) as! [String]
print (self.playerId);
}
However I'm having trouble assigning id from "userDetails". How do I take id from "userDetails" and assign it to self.playerId?
You can try something like this
if let dict = json?["userDetails"] as? [String:String] {
self.playerId = dict["id"]
}
Well the correct would be I believe:
guard let item = json?["userDetails"] as? [String: AnyObject],
self.playerId = item["id"] as? Int else {
return;
}
How to get JSON format from array? This is my JSON formatter
{
"productName": "Lemonade",
"transaction": ["[2016-08-01 10:23:42] - Get product in warehouse",
"[2016-08-01 10:53:22] - Sent to customer"]
}
I have an error with this code. I don't know how to get JSON format from transaction array.
if let jsonObject = try JSONSerialization.jsonObject(with: returnData, options: .allowFragments) as? [String: AnyObject]
{
valSucceeded = (jsonObject["succeeded"] as? Bool)!;
valResponseCode = (jsonObject["responseCode"] as? String)!;
valResponseDescription = (jsonObject["responseDescription"] as? String)!;
valSerialNumber = (jsonObject["serialNumber"] as? String)!;
valProductName = (jsonObject["productName"] as? String)!;
if let transactionsArray = jsonObject["transactions"] as? Array<AnyObject> {
for transact in transactionsArray
{
if let transactionStr = transact["transactions"] as? String {
valTransactions = transactionStr
} else {
valTransactions = ""
}
}
}
let entryResult = TraceModel(succeeded: valSucceeded,
responseCode: valResponseCode,
responseDescription: valResponseDescription,
serialNumber: valSerialNumber,
productName: valProductName,
transactions: valTransactions);
traceArray.append(entryResult);
}
I am trying to access items parsed in JSON from the iTunes API using Swift 3.0, but I am struggling to access the objects after they have been parsed. The objects are being parsed in this format:
{
resultCount = 50;
results = (
{
artistId = 70936;
artistName = "Johnny Cash";
artistViewUrl = "https://itunes.apple.com/us/artist/johnny-cash/id70936?uo=4";
artworkUrl100 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/100x100bb.jpg";
artworkUrl30 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/30x30bb.jpg";
artworkUrl60 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/60x60bb.jpg";
collectionCensoredName = "The Essential Johnny Cash";
collectionExplicitness = notExplicit;
collectionId = 251001680;
collectionName = "The Essential Johnny Cash";
collectionPrice = "14.99";
collectionViewUrl = "https://itunes.apple.com/us/album/ring-of-fire/id251001680?i=251002253&uo=4";
country = USA;
currency = USD;
discCount = 2;
discNumber = 1;
isStreamable = 1;
kind = song;
previewUrl = "http://a1144.phobos.apple.com/us/r1000/070/Music/b3/99/be/mzi.qvkhtgfg.aac.p.m4a";
primaryGenreName = Country;
releaseDate = "2002-02-12T08:00:00Z";
trackCensoredName = "Ring of Fire";
trackCount = 18;
trackExplicitness = notExplicit;
trackId = 251002253;
trackName = "Ring of Fire";
trackNumber = 15;
trackPrice = "1.29";
trackTimeMillis = 155707;
trackViewUrl = "https://itunes.apple.com/us/album/ring-of-fire/id251001680?i=251002253&uo=4";
wrapperType = track;
},
I want to be able to access the information from all 50 results, such as the artistName, for instance. This is my parsing function attempting to get the artistName and add it to my NSDictionary, but it keeps returning that it can't unwrap the dictionary.
func parser() {
let enteredText:String = (tbxSearch.text?.replacingOccurrences(of: " ", with: "+"))!
let url = "https://itunes.apple.com/search?term=\(enteredText)"
print(url)
guard let urlRequest = URL(string: url) else
{
print("Error creating endpoint")
return
}
let request = URLRequest(url: urlRequest)
URLSession.shared.dataTask(with: request) {(data,response,error) in
do
{
guard let data = data else
{
return
}
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else
{
return
}
if let results = json["results"] as? NSDictionary
{
self.avObjects.avDict.setValue("Artist Name", forKey: results["artistName"] as! String)
print(self.avObjects.avDict)
}
else
{
print("Couldn't unwrap the dictionary.")
}
print(json)
}
catch let error as NSError
{
print(error.debugDescription)
}
}.resume()
}
It looks like results is an array of dictionaries, not just a dictionary.
Instead of this: if let results = json["results"] as? NSDictionary
try this: if let results = json["results"] as? NSArray
You could then map or iterate over each element in the array, extracting "artistName" from each one, for example.
results is an array of dictionaries, not a dictionary itself. Try changing this:
if let results = json["results"] as? NSDictionary
to:
if let results = json["results"] as? NSArray
and then iterating over results. Each element of results is a dictionary with attributes such as artistName.
I am new on swift and I am getting a json back from a request but I can not parse. I am trying to get the json info and create coordinates to use on mapkit with annotations as well
Below is the json I get back
{
coord = [
{
islocationactive = 1;
latitude = "37.8037522";
locationid = 1;
locationsubtitle = Danville;
locationtitle = "Schreiner's Home";
longitude = "121.9871216";
},
{
islocationactive = 1;
latitude = "37.8191921";
locationid = 2;
locationsubtitle = "Elementary School";
locationtitle = Montair;
longitude = "-122.0071005";
},
{
islocationactive = 1;
latitude = "37.8186077";
locationid = 3;
locationsubtitle = "Americas Eats";
locationtitle = "Chaus Restaurant";
longitude = "-121.999046";
},
{
islocationactive = 1;
latitude = "37.7789669";
locationid = 4;
locationsubtitle = "Cheer & Dance";
locationtitle = Valley;
longitude = "-121.9829908";
}
] }
and my code to try to parse is this
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
//exiting if there is some error
if error != nil{
print("error is \(error)")
return;
}
//parsing the response
do {
//converting resonse to NSDictionary
var teamJSON: NSDictionary!
teamJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
print(teamJSON)
//getting the JSON array teams from the response
let liquidLocations: NSArray = teamJSON["coord"] as! NSArray
//looping through all the json objects in the array teams
for i in 0 ..< liquidLocations.count{
//getting the data at each index
// let teamId:Int = liquidLocations[i]["locationid"] as! Int!
}
} catch {
print(error)
}
}
//executing the task
task.resume()
but not that I try works. I want to get the latitude, longitude and create an annotationn on the map
Thanks for the help
You can try with below code its same as #Niko Adrianus Yuwono but made some changes so you will get teamid as integer
do {
let data : NSData = NSData() // change your data variable as you get from webservice response
guard let teamJSON = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: Any],
let liquidLocations = teamJSON["coord"] as? [[String: Any]]
else { return }
//looping through all the json objects in the array teams
for i in 0 ..< liquidLocations.count{
let teamId: Int = (liquidLocations[i]["locationid"] as! NSString).integerValue
print(teamId)
}
} catch {
print(error)
}
Try this
do {
guard let teamJSON = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any],
let liquidLocations = teamJSON["coord"] as? [[String: Any]]
else { return }
//looping through all the json objects in the array teams
for i in 0 ..< liquidLocations.count{
let teamId: Int = (liquidLocations[i]["locationid"] as! NSString).integerValue
}
} catch {
print(error)
}
The key is not to use NSDictionary and NSArray because it's not strongly-typed (Although you can make it strongly-typed too) use Swift's array and Dictionary where you can use [Element Type] for array and [Key: Value] for dictionary