parsing json objects with arrays in swift - ios

I have this JsonResponse:
...id = 7;
levels = (
{
name = "name";
"unique_id" = 23223;
},
{
name = "name";
"unique_id" = d32432;
},
{
name = "name";
"unique_id" = 324;
},
{
name = "name";
"unique_id" = 234;
}
);
I am using this to get result as a dictionary:
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary
MY question is how can i parse the levels array - iterating the objects and getting the array size

Basically you just loop through them:
if(jsonResult)
{
let levels = jsonResult! as NSDictionary;
for item in levels {
let obj = item as NSDictionary
let name = obj["name"] as NSString;
let uniqueId = obj["unique_id"] as NSNumber;
}
}

I would advise to use type safety as much as you can when using JSON. Here is an (untested) example to show you how you can cast safely the data:
if let levels = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? [[String: AnyObject]] {
for elem in levels {
let name = elem["name"] as? NSString
let uniqueId = elem["unique_id"] as? NSNumber
}
}

Related

Having difficulty parsing a response from an API call

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 {
}
}
}
}

How do I pluck this specific node out of from this JSON array?

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;
}

parsing json into an array in swift 3

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

how to extract a json object using swift?

JSON function:
func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &parseError)
if (parseError == nil){
if let coupon_list = json as? [String: AnyObject]{
if let coupons = coupon_list["data"] as? [AnyObject]{
for (var i = 0; i < coupons.count ; i++ ){
if let coupon_obj = coupons[i] as? NSDictionary{
let location: AnyObject? = coupon_obj.objectForKey("location")
//the print the value location
println(location)
//I just want to get the number keys before the value of the location
this is my Json object where you can see that
{
brand = "Mang Inasal";
category = (
2
);
desc = "Mang Inasal Salmonella Giveaway";
discount = 50;
"end_date" = 1443369600;
id = 2;
imgs = (
"http://mymegamobile.com/savvy/halo2x.png",
"http://mymegamobile.com/savvy/bar_filter.png",
"http://mymegamobile.com/savvy/bar_mega.png",
"http://mymegamobile.com/savvy/box1.png",
"http://mymegamobile.com/savvy/box2.png"
);
location = {
1435307555 = Baguio;
};
name = "Mang Inasal Halo Halo";
stamp = "2015-09-02 14:04:38";
"start_date" = 1438012800;
}
the result of the object structure is above.
How can I get the value of 1435307555 in my location?
You can do it this way:
let yourObject = location?.objectForKey("165952298") as! String
for (key,value) in coupon_list {
println(key)
}
This way you'll get all keys from the JSON
func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as! NSDictionary
if (parseError == nil) {
for (var i = 0; i < json.count ; i++ ) {
let location: AnyObject? = ((json)["location"] as! NSDictionary)["1435307555"]
//the print the value location
println(location)
}
}

How to remove item in String Array?

I have a JSON String like this:
let stringArray = "[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25},{\"url\":\"www.abc.com\",\"name\":\"tommy\",\"age\":23}]"
How can I remove one item(for example,tommy) in this string?
I tried to cast it to [[NSObject: AnyObject]] but always failed.
if let dictArray = stringArray as? [[NSObject: AnyObject]] {
} else {
println("failed") // print failed.
}
How can I get the result like this:
[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25}]
Convert your string to array because its JSON String
var stringArray = "[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25},{\"url\":\"www.abc.com\",\"name\":\"tommy\",\"age\":23}]"
var data : NSData = stringArray.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
var error: NSError?
var array = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as Array<AnyObject>
println(array)
Output :
[{
age = 25;
name = benson;
url = "www.abc.com";
}, {
age = 23;
name = tommy;
url = "www.abc.com";
}]
Now perform delete operation
array.removeAtIndex(1)
println(array)
Output :
[{
age = 25;
name = benson;
url = "www.abc.com";
}]
First convert your json string to swift array or dictionary;
let stringArray:String = "[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25},{\"url\":\"www.abc.com\",\"name\":\"tommy\",\"age\":23}]"
let data:NSData = stringArray.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!;
let dict:NSArray = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSArray;
NSLog("dict \(dict)");
Maybe you can cast the original jsons string to the dictionary then pick up the keys what your needs. as the sample code like :
if let json = NSJSONSerialization.JSONObjectWithData("your string to NSDATA",options:NSJSONReadingOptions.AllowFragments,$error){
// checks the son type and make sure the operation perform to the NSDictionary
var d = json as! NSDictionary;
// Picks the the values your want from d
}

Resources