Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
{
data = (
{
href = "XXX"
title = "YYY";
},
{
href = "XXX";
title = "YYY";
},
{
href = "XXX";
title = "YY";
}
);
}
Alamofire.request("http://apps.lowerauf.com.pk/news-app/geo2.php").responseJSON { response in
if let JSON = response.result.value{
JSON["data"]["href"]
}
}
I am using this code but it's not working and not showing anything.
Your data contains Array not the Dictionary, so you need to loop through the data array and then access each nested JSON from it.
Alamofire.request("http://apps.lowerauf.com.pk/news-app/geo2.php").responseJSON { response in
//Considering you are using SwiftyJSON
if let json = JSON(response.result.value) {
for data in json["data"].arrayValue {
print(data["href"])
}
}
}
Response JSON is Dictionary and data is an array of dictionary ..
if let json = response.result.value as? [String:Any]{
if let data = json["data"] as? [[String:String]] {
for value in data {
print(value["href"])
}
}
}
your data is array
if let json = response.result.value as? [String:Any]{
if let data = json["data"] as? [[String:String]] {
for value in data {
print(value["href"])}
} }
Related
I'm having a name value to my tableviewcell like so..
for asd in orderDetails {
if let jsonStr = asd.value(forKey: "customerJson") as? String {
let data = jsonStr?.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any] {
for item in json {
if item.key == "first_Name" {
cell.nameLabel.text = item.value as? String //ASSIGNED HERE
}
}
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
}
Now I want to search on the search bar based on this name. While searching in other cases where the core data attributes were mentioned directly I did something like so which worked fine..
filtered = self.newProdDetails.filter({( data : NewProduct) -> Bool in
return (data.name?.lowercased().contains(searchText.lowercased()))! //Here the entity NewProduct has an attribute name
})
But in the current scenario, the attribute is a json string called customer_json given like so and I wanted to filter based on the first_name..
customer_json={
"mobile_number”:”9876543210”,
"first_name”:”testName”,
"last_name”:”testLastName”,
"seller_id":"93"
}
simply parse your JSON into the array or dictionary a/c to json with help :
let arrayJson = JSONSerialization.jsonObject(with:....
.....
then apply Search simply on an array like this :
let filterArr = arrayJson.filter {
return (($0["first_name"] as! String).lowercased().contains(searchText.lowercased()))
}
Hi I'm trying to get data from a certain JSON API. I can gat a snapshot of all values from the API, which is shown below. But I can't manage to put a specifiek row in a variable. This is the JSON form which I get. I want to print the "Description" value.Can someone help me with this?
And Hier is my code:
func apiRequest() {
let config = URLSessionConfiguration.default
let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
let password = "G23#rE9t1#"
let loginString = String(format: "%#:%#", username, password)
let userPasswordData = loginString.data(using: String.Encoding.utf8)
let base64EncodedCredential = userPasswordData?.base64EncodedString()
let authString = "Basic " + (base64EncodedCredential)!
print(authString)
config.httpAdditionalHeaders = ["Authorization" : authString]
let session = URLSession(configuration: config)
var running = false
let url = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")
let task = session.dataTask(with: url! as URL) {
( data, response, error) in
if let taskHeader = response as? HTTPURLResponse {
print(taskHeader.statusCode)
}
if error != nil {
print("There is an error!!!")
print(error)
} else {
if let content = data {
do {
let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(array)
if let items = array["items"] {
if let description = items["Description"] as? [[String:Any]]{
print(description as Any)
}
}
}
catch {
print("Error: Could not get any data")
}
}
}
running = false
}
running = true
task.resume()
while running {
print("waiting...")
sleep(1)
}
}
First of all the array is not an array and not AnyObject, it's a dictionary which is [String:Any] in Swift 3.
let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
print(dictionary)
I don't know why all tutorials suggest .mutableContainers as option. That might be useful in Objective-C but is completely meaningless in Swift. Omit the parameter.
The object for key itemsis an array of dictionaries (again, the unspecified JSON type in Swift 3 is Any). Use a repeat loop to get all description values and you have to downcast all values of a dictionary from Any to the expected type.
if let items = dictionary["items"] as? [[String:Any]] {
for item in items {
if let description = item["Description"] as? String {
print(description)
}
}
}
Looks like items is an array that needs to be looped through. Here is some sample code, but I want to warn you that this code is not tested for your data.
if let items = array["items"] as? [[String: AnyObject]] {
for item in items {
if let description = item["Description"] as? String{
print("Description: \(description)")
}
}
}
This code above, or some variation of it, should get you on the right track.
use the SwiftyJSON and it would be as easy as json["items"][i].arrayValue as return and array with items Values or json["items"][i]["description"].stringValue to get a string from a row
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am working on parsing a JSON response, I need to get data from the key FILES, but code is not working
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
if let name = json["LIBRARY"] as? [[String : AnyObject]]{
if let files = name["FILES"] as? [[String : AnyObject]]{
for file in files {
var info = Modal()
info.audioUrl = file["SRC"] as? String
print(info.audioUrl)
self.modals.append(info)
}
}
}
} catch let error {
print(error)
}
I think in your code name is an array so to get files instance you should replace your code with:
if let namesArray = json["LIBRARY"] as? [[String : AnyObject]]{
for name in namesArray {
if let filesArray = name["FILES"] as? [[String : AnyObject]] {
for file in filesArray {
print(file["SRC"])
}
}
}
}
First of all in Swift 3 the standard JSON dictionary is [String:Any].
Since the value for key LIBRARY is (correctly parsed) an array, you have to subscript the array by index
if let library = json["LIBRARY"] as? [[String : Any]], !library.isEmpty {
if let files = library[0]["FILES"] as? [[String : Any]] {
And – as always – .mutableContainers is completely meaningless in Swift, omit the parameter,
Im using Swift 3 and Alamofire 4.0. I am able to print out the entire response but I am having trouble looping through and printing out each value. I am getting a " Type 'NSFastEnumerationIterator.Element' (aka 'Any') has no subscript members when I try to print out 'title' below. Any help is greatly appreciated.
Alamofire.request(url).responseJSON { response in
if let dict = response.result.value as? Dictionary<String, AnyObject> {
if let datas = dict["data"] as? NSArray{
for data in datas{
print("DEVELOPER: \(data)")
if let title = data["myTitle"] as? String{
print(title)
}
}
}
}
}
Just use native Swift Array. Use always Swift native types unless you have absolutely no choice. NSArray lacks type information so the compiler cannot infer that the array contains dictionaries.
if let datas = dict["data"] as? [[String:Any]] {
Sometimes you wanna keep your data as structured, all you have to do is check for the dictionary itself while in loop like the following:
for apple in apples {
if let _ = apple as? [String:AnyObject] {
// do whatever you like here
}
}
While fetching data from api I can get response either array of products or dictionary with error for e.g.
If everything went right api sends array of products as:
[
"Product1":
{
name = "someting",
price = 100,
discount = 10%,
images = [image1,image2]
},
"Product2":
{
name = "someting",
price = 100,
discount = 10%,
images = [image1,image2]
}
]
But if some error occur it sends dictionary with error message and code as:
{
error_message = "message"
error_code = 202
}
I am using this code to convert JSON data to array:
do {
let jsonDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray{
//Some code....
} catch let error as NSError {
print("JSON Error: \(error.localizedDescription)")
}
but if I get error as dictionary it crash.
Problems:
1. How to know whether received data is an array or dictionary ?
2. Some time even key or value can be missing so checking for value it becomes very lengthy code like:
if let productsArray = jsonObject as? NSArray{
if let product1 = productsArray[0] as? NSDictionary{
if let imagesArray = product1["image"] as? NSArray{
if let imageUrl = imagesArray[0] as? String{
//Code ....
}
}
}
}
I read about guard keyword to reduce if condition but I don't have clear idea how to use here.
Problem 1:
For try catch , add an if let for casting the object as NSDictionary or NSArray like :
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
if let jsonDict = jsonObject as? NSDictionary {
// Do smthg.
}
if let jsonArray = jsonObject as? NSArray {
// Do smthg.
}
}catch {
//...
}
For Problem 2:
I think guard won't help you . It needs smthg like return / break in its else statement. If you don't want to throw your methods if one of your values isn't available you have to use this lengthy if let code style.
Maybe in your case best practice would be setting up a Data Model for Product with optional properties.
Class product {
var name:String?
var image:[NSData]? // maybe UIImage or smthg.
var price:Int?
var discount:Int?
init(jsonDic:NSDictionary){
// if it's not there it would be nil
self.name = jsonDic["name"] as? String
self.image = jsonDic["image"] as? NSArray
self.discount = jsonDic["discount"] as? Int
self.price = jsonDic["price"] as? Int
}
}
Now you can load those models with your data without the if let etc..
But if you wanna read those values you have to use the if let for checkin if its not nil.
For init in your case it should be something like this:
Add this into the if let statement of the do catch block ( ... as? NSArray // DO smthg. )
for item in jsonArray {
guard let jsonDic = item as? NSDictionary else { return }
// if you dont know every key you can just iterate through this dictionary
for (_,value) in jsonDic {
guard let jsonDicValues = value as? NSDictionary else { return }
productArray.append(Product(jsonDic: jsonDicValues)
}
}
As i said , know you got the whole if let stuff when reading from the model an not when writing ( reading the json )
You have a few things going on here, one, I would analyze your server's http response status code and only attempt to process data if you received a status code indicating you will have good data
// In practical scenarios, this may be a range
if statusCode != 200 {
// Handle a scenario where you don't have good data.
return
}
Secondly, I'd guard against the response, it looks like you have named it "data" like so:
guard let receivedData = data else {
return
}
From this point on, you can use the receivedData constant.
Here'd I'd attempt to use NSJSONSeralization, like you do, but by casting it into a Swift dictionary, like so:
if let responseDictionary = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? [String:AnyObject] {
// Here you can try to access keys on the response
// You can try things like
let products = responseDictionary?["products"] as? [[String:AnyObject]]
for product in products {
let productName = product["name"] as? String
if productName == nil {
continue
}
let newProduct = Product(name: productName)
// Do something with newly processed data
}
}
I tried to be general and also show you a guard example.
first of all I recommend using SwiftyJSON pod or the class straight into your Xcode, it works like a charm and you won't need to cast things down to figure whether you have a string or a dictionary or whatever. It is gold.
Once you've got your JSON, you can use this recursive function I created that does exactly what you need. It turns any Json into a dictionary. I mostly use it to save data into Firebase, without having to parse everything.
After you have imported SwiftyJSON into your project and added import SwiftyJSON to your Swift file you can:
//JSON is created using the awesome SwiftyJSON pod
func json2dic(_ j: JSON) -> [String:AnyObject] {
var post = [String:AnyObject]()
for (key, object) in j {
post[key] = object.stringValue as AnyObject
if object.stringValue == "" {
post[key] = json2dic(object) as AnyObject
}
}
return post
}
let json = JSON(value) // Value is the json structure you received from API.
var myDictionary = [String:AnyObject]()
myDictionary = json2dic(json)
You can catch the class of your response. If your response is kind of class dictionary, assign it as dictionary else if your response is kind of class array, assign it to array. Good luck.