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,
Related
hello i'm new to swift and I have responseJson from alamofire consist of jsonArray contain jsonObjects like this
[{"id":"1","name":"person1"},{"id":"2","name":"person2"}]
how i can parse it into array of this custom model
class Person {
var name : String
var id : String
}
i've done a much searching but can't find case identical to mine and i can't use Codable because i'm using xcode 8 and not able to upgrade my xcode version to 9 now
I'm getting the response like this
Alamofire.request(url).responseJSON{ response in
if(response.result.isSuccess)
{
if let jsonarray = response.result.value as? [[String: Any]]
{
//what to do here ?
}
}
}
if let jsonarray = response.result.value as? [[String: Any]]{
//what to do here ?
var persons:[Person] = []
for userDictionary in jsonarray{
guard let id = userDictionary["id"] as? String, let name = userDictionary["name"] as? String else { continue }
persons.append(Person(id, name))
}
//Persons complete.
}
Use guard else for the required variables.
If there are additional variables that could be optional, like var age:Int? in Person, you could do like this:
for userDictionary in jsonarray{
guard let id = userDictionary["id"] as? String, let name = userDictionary["name"] as? String else { continue }
let age = userDictionary["age"] as? Int
persons.append(Person(id, name, age))
}
#Tony,
In swift4 you can codable protocol to parsing the JSON that helps in writing generic code. Suppose if in future requirement came to add dob than its very simple.
And in swift3 you can use object mapper class for same.
If you need more help than please let me know.
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"])}
} }
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 6 years ago.
Improve this question
I am having some issues getting the following code to work, any ideas why it doesn't work?
guard let parsedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments),
let parsedDict = parsedData as? [String:Any],
let stop = parsedDict["Stop"] as? [String:Any],
let name = stop["Name"] as? String,
let latitude = stop["Latitude"] as? String,
let longitude = stop["Longitude"] as? String else
{
print("Something Went Wrong")
return
}
nameArray.append(name)
latArray.append(latitude)
longArray.append(longitude)
However, the following code does work:
if let parsedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
{
if let stop = parsedData?["Stop"] as? [String:Any]
{
if let latitude = stop["Latitude"] as? String, let longitude = stop["Longitude"] as? String, let name = stop["Name"] as? String
{
nameArray.append(name)
latArray.append(latitude)
longArray.append(longitude)
}
}
}
EDIT
After reviewing the code, the issue seems to stem from this line:
guard let stop = parsedDict["Stop"] as? [String:Any] else
{
print("Something went wrong")
return
}
When running this I receive "Something went wrong" in the console, however when running
if let stop = parsedData?["Stop"] as? [String:Any]
{
print(stop)
}
I get a valid print of stop.
Running your guard example myself in a playground is successful for me. I would recommend breaking up your guard into multiple logical sections. For example to help you track down your error you could change it to:
//Note: You should not force unwrap data here
guard let parsedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) else{
print("Serialization error"); return
}
guard
let parsedDict = parsedData as? [String:Any],
let stop = parsedDict["Stop"] as? [String:Any] else {
print("Error casting to dictionary"); return
}
guard
let name = stop["Name"] as? String,
let latitude = stop["Latitude"] as? String,
let longitude = stop["Longitude"] as? String else {
print("Error casting dictionary values"); return
}
//Everything is ok here
This question already has answers here:
Swift 3 JSON NSFastEnumerationIterator has no subscript members
(2 answers)
Closed 6 years ago.
Trying to parse a JSON array in iOS swift 3.0. But in XCode I always get to see this error:
Type 'NSFastEnumerationIterator.Element' (aka 'Any') has no subscript members
The array I am trying to parse looks something like this:
[{"area_code":1,"area_name":"value"},{"area_code":2,"area_name":"value"},{"area_code":3,"area_name":"value"},{"area_code":4,"area_name":"value"}]
The code snippet of iOS looks something like this.
let json = try!JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as? NSArray
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
for dayData in parseJSON{
let areaObj = AreaCode()
if let areaCode = dayData["area_code"] as? Int{
areaObj.areaCode = areaCode
}
if let areaName = dayData["area_name"] as? String{
areaObj.areaName = areaName
}
areaCodeArray.append(areaObj)
}
DispatchQueue.main.async(execute: {
// perform on main
self.onGetAreaList("Success");
});
}
Try this way using [[String:Any]] instead NSArray
let json = try! JSONSerialization.jsonObject(with: data!, options: []) as? [[String:Any]]
for dayData in json{
let areaObj = AreaCode()
if let areaCode = dayData["area_code"] as? Int{
areaObj.areaCode = areaCode
}
if let areaName = dayData["area_name"] as? String{
areaObj.areaName = areaName
}
areaCodeArray.append(areaObj)
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
}
}