SwiftyJSON Reading JSON Array issue - json

I'm trying to read a json array data as below with my code but I'm getting empty result all the time while I can print the whole data. Please where would be my issue?
I've read this topic but I couldn't get the result. Topic Link
{"Cars":[{"Brand":"Alfa Romeo"},{"Brand":"Audi"},{"Brand":"BMW"},{"Brand":"Citroen"},{"Brand":"Dacia"},{"Brand":"Fiat"},..........
My code
func getData(){
var url = "http://test.net/services/test.php"
var request = HTTPTask()
request.GET(url, parameters: nil, completionHandler:
{
(response:HTTPResponse) in
var jsonData = response.responseObject as! NSData
var json = JSON(data: jsonData)
println("All data \(json)")
dispatch_async(dispatch_get_main_queue(),
{
println(json["Cars"]["Brand"].stringValue)
})
})
}

json["Cars"] is an array, so for example to get the first item via SwiftyJSON:
println(json["Cars"][0]["Brand"].stringValue)
In a JSON string, { and } are delimiters for dictionaries, whereas [ and ] are delimiters for arrays.
EDIT:
Following your comment, yes, you can loop over the array:
if let cars = json["Cars"].array {
for car in cars {
println(car["Brand"])
}
}

This way you can get your json objects using SwiftyJSON:
//Get your Data First
let json = JSON(data: data)
//Store your values from car key into Car object so we can get total count.
let Cars = json["Cars"].arrayValue
//Use For loop to get your car Brand
for i in 0..<Cars.count
{
println(json["Cars"][i]["Brand"].stringValue)
}
And your output will be:
Alfa Romeo
Audi
BMW
Citroen
Dacia
Fiat
Hope this is what you need.

Related

Swift - JSON array values

I am getting following JSON values in output:
[["category_title": Shelly], ["category_title": Thaddeus],
["category_title": Chantale], ["category_title": Adara],
["category_title": Mariko], ["category_title": Felicia]]
But I want it like below:
["Shelly","Thaddeus","Chantale", "Adara","Mariko","Felicia"]
I have the following Swift code. Please help me get above output.
func successGetTermsData(response: Any){
var UserRole : String = ""
var arrayOfDetails = response as? [[String: Any]] ?? []
UserRole = arrayOfDetails as? String ?? ""
print(arrayOfDetails)
}
You have to map the array of Dictionary arrayOfDetails to an array of String. flatMap ignores a missing key.
if let arrayOfDetails = response as? [[String: String]] {
let userRole = arrayOfDetails.flatMap { $0["category_title"] }
print(userRole)
}
There are many ways to do this. One way is to use flatmap to get just the values in your array of dictionaries:
let arrayOfValues = arrayOfDetails.flatMap { $0.values }
In order to get this to work, the names need to be inside double quotes: "Shelly", etc.

How to parse JSON data and eliminate duplicates in Swift?

I have a very large JSON file that I have downloaded from the web, and I need to parse this in Swift. The JSON construction is an array of dictionaries. Each dictionary object contains a key of "phone" (referring to the phone number), and whose value is the actual phone number in the form of a string.
What I would like to do, is iterate through the entire list of dictionary objects in the array, and ensure that there are no dictionary objects that have the same value for the key, "phone". If a duplicate is found, I would like to eliminate it from the list, and print it out to the console.
Here is the relevant code that I have:
guard let json = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else {
print("error")
return
}
for dict in json! {
//This is where I would do the check
}
How would I accomplish this?
You can do as
var ph = [String]()
var newjson = [[String:String]]()
for dict in json {
if ph.contains(dict["Phone"]!) {
print("duplicate phone \(dict["Phone"]!)")
} else {
ph.append(dict["Phone"]!)
newjson.append(dict)
}
}
print(newjson)
Hare newjson is the new array of dictionary that do not have duplicate phone
Use the array extension method to remove the duplicates from the json object
extension Array where Element: Equatable {
mutating func removeDuplicates() {
var result = [Element]()
for value in self {
if !result.contains(value) {
result.append(value)
}
}
self = result
}
}
Alamofire.request(apiURL, method: .get, parameters:parameters, headers:headers)
.responseJSON { response in
if let result = response.result.value {
let json = JSON(result)
var listArray = json["somekey"].arrayValue
listArray.removeDuplicates()
print(listArray)
}
}

Retrieving values from 2D array in JSON string

We fetch some JSON data using a REST protocol like this.
jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
Which looks like this:
jsonResult: (
{
board = "[[\"1:\",\"Y\",\"U\",\"P\"]]";
})
From this we get a game board like so:
if let boardContentArray = jsonResult[0]["board"] as NSArray?{
print("boardContentArray: \(boardContentArray)" )
} else {
print("board element is not an NSArray")
}
The boardContentArray looks like this: It i supposed to be a 2D array with only one row and four columns at the moment, but it should should work for any given size.
[["1:","Y","U","P"]]
How can you retrieve the individual values of boardFromRemote. I imagine to get the element at 0,0 in the 2D array some way like this:
boardContentArray[0][0]
This should then return "1:", which is not the case. This exact syntax is incorrect and won't compile. What is the correct way to retrieve an element from the boardContentArray variable?
The content of jsonResult[0]["board"] is a JSON String which can be decoded as an array with NSJSONSerialization. You have to first transform the String to NSData, then decode it like this for example:
do {
let boardContentArray = "[[\"1:\",\"Y\",\"U\",\"P\"]]" // the String from jsonResult[0]["board"]
if let boardData = boardContentArray.dataUsingEncoding(NSUTF8StringEncoding),
let boardArray = try NSJSONSerialization.JSONObjectWithData(boardData, options: []) as? [[String]] {
print(boardArray[0]) // ["1:", "Y", "U", "P"]
}
} catch let error as NSError {
print(error)
}

JSON with Swift 2, Array Structure

I'm Having trouble with JSON and Swift 2.
I'm getting this Array from the server
[{"KidName":"Jacob","KidId":1,"GardenID":0},
{"KidName":"Sarah","KidId":2,"GardenID":0},
{"KidName":"Odel","KidId":3,"GardenID":0}]
I'm familiar with JSON and I know it's not the recommended way to get a JSON, since it's supposed to be something like
{"someArray":[{"KidName":"Jacob","KidId":1,"gardenID":0}, .....
So my first question is it possible to run over the first JSON I've post and get the KidName number without editing the JSON and Add to it a JSON OBJECT to hold the array ?
my second question is really with Swift 2, how can I get the KidName (after I've edited the JSON to have an holder for the array)?
this is my code... (please read the Notes I've added)
BTW, I'm familiar with SwiftyJSON as well...
// Method I've build to get the JSON from Server, the Data is the JSON
sendGetRequest { (response, data ) -> Void in
// need to convert data to String So I can add it an holder
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
/**
after editing the str, i'm Having a valid JSON, let's call it fixedJSON
*/
let fixedJSON = "{\"kidsArray\":\(dropLast)}"
// Now I'm converting it to data back again
let jsonTodata = fixedJSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
// After Having the data, I need to convert it to JSON Format
do{
let dataToJson = try NSJSONSerialization.JSONObjectWithData(jsonTodata, options: []) as! [String:AnyObject]
//Here I'm getting the KidID
if let kidID = jsonSe["kidsArray"]![0]["KidId"]!!.integerValue {
print("kidID in first index is: \(kidID)\n")
}
//NOW trying to get the KidName which not working
if let kidname = jsonSe["kidsArray"]![0]["KidName"]!!.stringValue {
print("KidName is \(kidname)\n")
}
}
So as you can see, I'm not able to get the KidName.
Any Help Would be Appreciate.
You can use the following function to get the 'someArray' array and then use this getStringFromJSON function to get the 'KidName' value.
func getArrayFromJSON(data: NSDictionary, key: String) -> NSArray {
if let info = data[key] as? NSArray {
return info
}
else {
return []
}
}
let someArray = self.getArrayFromJSON(YourJSONArray as! NSDictionary, key: "someArray")
func getStringFromJSON(data: NSDictionary, key: String) -> String {
if let info = data[key] as? String {
return info
}
return ""
}
let KidName = self.getStringFromJSON(someArray as! NSDictionary, key: "KidName")
Hope this might be useful to you.

How to get array from nsdisctionary swift

I have below json object. i am parsing json and storing this as disctionary. now i want to get these array from disctionary but when i am using objectForKey("upcomingAppointments") it given me nothing
{
"upcomingAppointments": [],
"upcomingFollowUps": [],
"followUps": []
}
Try this:
var dictionary = //NSDictionary from somewhere...
if let upcomingAppointments = dictionary["upcomingAppointments"] as? NSArray {
//Process your appointments here.
}
//Same goes for other such json fields.